Skip to content

Commit eaf5b65

Browse files
committed
Auto merge of rust-lang#97004 - nnethercote:proc-macro-tweaks, r=eddyb
Proc macro tweaks Various improvements I spotted while looking through the proc macro code. r? `@eddyb`
2 parents 2114174 + 8e0c04c commit eaf5b65

File tree

7 files changed

+114
-113
lines changed

7 files changed

+114
-113
lines changed

proc_macro/src/bridge/buffer.rs

+24-24
Original file line numberDiff line numberDiff line change
@@ -6,37 +6,37 @@ use std::ops::{Deref, DerefMut};
66
use std::slice;
77

88
#[repr(C)]
9-
pub struct Buffer<T: Copy> {
10-
data: *mut T,
9+
pub struct Buffer {
10+
data: *mut u8,
1111
len: usize,
1212
capacity: usize,
13-
reserve: extern "C" fn(Buffer<T>, usize) -> Buffer<T>,
14-
drop: extern "C" fn(Buffer<T>),
13+
reserve: extern "C" fn(Buffer, usize) -> Buffer,
14+
drop: extern "C" fn(Buffer),
1515
}
1616

17-
unsafe impl<T: Copy + Sync> Sync for Buffer<T> {}
18-
unsafe impl<T: Copy + Send> Send for Buffer<T> {}
17+
unsafe impl Sync for Buffer {}
18+
unsafe impl Send for Buffer {}
1919

20-
impl<T: Copy> Default for Buffer<T> {
20+
impl Default for Buffer {
2121
fn default() -> Self {
2222
Self::from(vec![])
2323
}
2424
}
2525

26-
impl<T: Copy> Deref for Buffer<T> {
27-
type Target = [T];
28-
fn deref(&self) -> &[T] {
29-
unsafe { slice::from_raw_parts(self.data as *const T, self.len) }
26+
impl Deref for Buffer {
27+
type Target = [u8];
28+
fn deref(&self) -> &[u8] {
29+
unsafe { slice::from_raw_parts(self.data as *const u8, self.len) }
3030
}
3131
}
3232

33-
impl<T: Copy> DerefMut for Buffer<T> {
34-
fn deref_mut(&mut self) -> &mut [T] {
33+
impl DerefMut for Buffer {
34+
fn deref_mut(&mut self) -> &mut [u8] {
3535
unsafe { slice::from_raw_parts_mut(self.data, self.len) }
3636
}
3737
}
3838

39-
impl<T: Copy> Buffer<T> {
39+
impl Buffer {
4040
pub(super) fn new() -> Self {
4141
Self::default()
4242
}
@@ -53,7 +53,7 @@ impl<T: Copy> Buffer<T> {
5353
// because in the case of small arrays, codegen can be more efficient
5454
// (avoiding a memmove call). With extend_from_slice, LLVM at least
5555
// currently is not able to make that optimization.
56-
pub(super) fn extend_from_array<const N: usize>(&mut self, xs: &[T; N]) {
56+
pub(super) fn extend_from_array<const N: usize>(&mut self, xs: &[u8; N]) {
5757
if xs.len() > (self.capacity - self.len) {
5858
let b = self.take();
5959
*self = (b.reserve)(b, xs.len());
@@ -64,7 +64,7 @@ impl<T: Copy> Buffer<T> {
6464
}
6565
}
6666

67-
pub(super) fn extend_from_slice(&mut self, xs: &[T]) {
67+
pub(super) fn extend_from_slice(&mut self, xs: &[u8]) {
6868
if xs.len() > (self.capacity - self.len) {
6969
let b = self.take();
7070
*self = (b.reserve)(b, xs.len());
@@ -75,7 +75,7 @@ impl<T: Copy> Buffer<T> {
7575
}
7676
}
7777

78-
pub(super) fn push(&mut self, v: T) {
78+
pub(super) fn push(&mut self, v: u8) {
7979
// The code here is taken from Vec::push, and we know that reserve()
8080
// will panic if we're exceeding isize::MAX bytes and so there's no need
8181
// to check for overflow.
@@ -90,7 +90,7 @@ impl<T: Copy> Buffer<T> {
9090
}
9191
}
9292

93-
impl Write for Buffer<u8> {
93+
impl Write for Buffer {
9494
fn write(&mut self, xs: &[u8]) -> io::Result<usize> {
9595
self.extend_from_slice(xs);
9696
Ok(xs.len())
@@ -106,35 +106,35 @@ impl Write for Buffer<u8> {
106106
}
107107
}
108108

109-
impl<T: Copy> Drop for Buffer<T> {
109+
impl Drop for Buffer {
110110
fn drop(&mut self) {
111111
let b = self.take();
112112
(b.drop)(b);
113113
}
114114
}
115115

116-
impl<T: Copy> From<Vec<T>> for Buffer<T> {
117-
fn from(mut v: Vec<T>) -> Self {
116+
impl From<Vec<u8>> for Buffer {
117+
fn from(mut v: Vec<u8>) -> Self {
118118
let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity());
119119
mem::forget(v);
120120

121121
// This utility function is nested in here because it can *only*
122122
// be safely called on `Buffer`s created by *this* `proc_macro`.
123-
fn to_vec<T: Copy>(b: Buffer<T>) -> Vec<T> {
123+
fn to_vec(b: Buffer) -> Vec<u8> {
124124
unsafe {
125125
let Buffer { data, len, capacity, .. } = b;
126126
mem::forget(b);
127127
Vec::from_raw_parts(data, len, capacity)
128128
}
129129
}
130130

131-
extern "C" fn reserve<T: Copy>(b: Buffer<T>, additional: usize) -> Buffer<T> {
131+
extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer {
132132
let mut v = to_vec(b);
133133
v.reserve(additional);
134134
Buffer::from(v)
135135
}
136136

137-
extern "C" fn drop<T: Copy>(b: Buffer<T>) {
137+
extern "C" fn drop(b: Buffer) {
138138
mem::drop(to_vec(b));
139139
}
140140

proc_macro/src/bridge/client.rs

+27-23
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,9 @@ macro_rules! define_handles {
4949
#[repr(C)]
5050
pub(crate) struct $oty {
5151
handle: handle::Handle,
52-
// Prevent Send and Sync impls
52+
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual
53+
// way of doing this, but that requires unstable features.
54+
// rust-analyzer uses this code and avoids unstable features.
5355
_marker: PhantomData<*mut ()>,
5456
}
5557

@@ -133,7 +135,9 @@ macro_rules! define_handles {
133135
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
134136
pub(crate) struct $ity {
135137
handle: handle::Handle,
136-
// Prevent Send and Sync impls
138+
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual
139+
// way of doing this, but that requires unstable features.
140+
// rust-analyzer uses this code and avoids unstable features.
137141
_marker: PhantomData<*mut ()>,
138142
}
139143

@@ -191,7 +195,7 @@ define_handles! {
191195
// FIXME(eddyb) generate these impls by pattern-matching on the
192196
// names of methods - also could use the presence of `fn drop`
193197
// to distinguish between 'owned and 'interned, above.
194-
// Alternatively, special 'modes" could be listed of types in with_api
198+
// Alternatively, special "modes" could be listed of types in with_api
195199
// instead of pattern matching on methods, here and in server decl.
196200

197201
impl Clone for TokenStream {
@@ -250,17 +254,17 @@ macro_rules! define_client_side {
250254
$(impl $name {
251255
$(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
252256
Bridge::with(|bridge| {
253-
let mut b = bridge.cached_buffer.take();
257+
let mut buf = bridge.cached_buffer.take();
254258

255-
b.clear();
256-
api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
257-
reverse_encode!(b; $($arg),*);
259+
buf.clear();
260+
api_tags::Method::$name(api_tags::$name::$method).encode(&mut buf, &mut ());
261+
reverse_encode!(buf; $($arg),*);
258262

259-
b = bridge.dispatch.call(b);
263+
buf = bridge.dispatch.call(buf);
260264

261-
let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
265+
let r = Result::<_, PanicMessage>::decode(&mut &buf[..], &mut ());
262266

263-
bridge.cached_buffer = b;
267+
bridge.cached_buffer = buf;
264268

265269
r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
266270
})
@@ -367,7 +371,7 @@ pub struct Client<F> {
367371
// FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
368372
// a wrapper `fn` pointer, once `const fn` can reference `static`s.
369373
pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
370-
pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>,
374+
pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer,
371375
pub(super) f: F,
372376
}
373377

@@ -377,22 +381,22 @@ pub struct Client<F> {
377381
fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
378382
mut bridge: Bridge<'_>,
379383
f: impl FnOnce(A) -> R,
380-
) -> Buffer<u8> {
384+
) -> Buffer {
381385
// The initial `cached_buffer` contains the input.
382-
let mut b = bridge.cached_buffer.take();
386+
let mut buf = bridge.cached_buffer.take();
383387

384388
panic::catch_unwind(panic::AssertUnwindSafe(|| {
385389
bridge.enter(|| {
386-
let reader = &mut &b[..];
390+
let reader = &mut &buf[..];
387391
let input = A::decode(reader, &mut ());
388392

389393
// Put the `cached_buffer` back in the `Bridge`, for requests.
390-
Bridge::with(|bridge| bridge.cached_buffer = b.take());
394+
Bridge::with(|bridge| bridge.cached_buffer = buf.take());
391395

392396
let output = f(input);
393397

394398
// Take the `cached_buffer` back out, for the output value.
395-
b = Bridge::with(|bridge| bridge.cached_buffer.take());
399+
buf = Bridge::with(|bridge| bridge.cached_buffer.take());
396400

397401
// HACK(eddyb) Separate encoding a success value (`Ok(output)`)
398402
// from encoding a panic (`Err(e: PanicMessage)`) to avoid
@@ -403,24 +407,24 @@ fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
403407
// this is defensively trying to avoid any accidental panicking
404408
// reaching the `extern "C"` (which should `abort` but might not
405409
// at the moment, so this is also potentially preventing UB).
406-
b.clear();
407-
Ok::<_, ()>(output).encode(&mut b, &mut ());
410+
buf.clear();
411+
Ok::<_, ()>(output).encode(&mut buf, &mut ());
408412
})
409413
}))
410414
.map_err(PanicMessage::from)
411415
.unwrap_or_else(|e| {
412-
b.clear();
413-
Err::<(), _>(e).encode(&mut b, &mut ());
416+
buf.clear();
417+
Err::<(), _>(e).encode(&mut buf, &mut ());
414418
});
415-
b
419+
buf
416420
}
417421

418422
impl Client<fn(crate::TokenStream) -> crate::TokenStream> {
419423
pub const fn expand1(f: fn(crate::TokenStream) -> crate::TokenStream) -> Self {
420424
extern "C" fn run(
421425
bridge: Bridge<'_>,
422426
f: impl FnOnce(crate::TokenStream) -> crate::TokenStream,
423-
) -> Buffer<u8> {
427+
) -> Buffer {
424428
run_client(bridge, |input| f(crate::TokenStream(input)).0)
425429
}
426430
Client { get_handle_counters: HandleCounters::get, run, f }
@@ -434,7 +438,7 @@ impl Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
434438
extern "C" fn run(
435439
bridge: Bridge<'_>,
436440
f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
437-
) -> Buffer<u8> {
441+
) -> Buffer {
438442
run_client(bridge, |(input, input2)| {
439443
f(crate::TokenStream(input), crate::TokenStream(input2)).0
440444
})

proc_macro/src/bridge/closure.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ use std::marker::PhantomData;
66
pub struct Closure<'a, A, R> {
77
call: unsafe extern "C" fn(*mut Env, A) -> R,
88
env: *mut Env,
9-
// Ensure Closure is !Send and !Sync
9+
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
10+
// this, but that requires unstable features. rust-analyzer uses this code
11+
// and avoids unstable features.
12+
//
13+
// The `'a` lifetime parameter represents the lifetime of `Env`.
1014
_marker: PhantomData<*mut &'a mut ()>,
1115
}
1216

proc_macro/src/bridge/handle.rs

+3
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ use std::sync::atomic::{AtomicUsize, Ordering};
88

99
pub(super) type Handle = NonZeroU32;
1010

11+
/// A store that associates values of type `T` with numeric handles. A value can
12+
/// be looked up using its handle.
1113
pub(super) struct OwnedStore<T: 'static> {
1214
counter: &'static AtomicUsize,
1315
data: BTreeMap<Handle, T>,
@@ -49,6 +51,7 @@ impl<T> IndexMut<Handle> for OwnedStore<T> {
4951
}
5052
}
5153

54+
/// Like `OwnedStore`, but avoids storing any value more than once.
5255
pub(super) struct InternedStore<T: 'static> {
5356
owned: OwnedStore<T>,
5457
interner: HashMap<T, Handle>,

proc_macro/src/bridge/mod.rs

+6-5
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ macro_rules! with_api {
176176
}
177177

178178
// FIXME(eddyb) this calls `encode` for each argument, but in reverse,
179-
// to avoid borrow conflicts from borrows started by `&mut` arguments.
179+
// to match the ordering in `reverse_decode`.
180180
macro_rules! reverse_encode {
181181
($writer:ident;) => {};
182182
($writer:ident; $first:ident $(, $rest:ident)*) => {
@@ -224,15 +224,17 @@ use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
224224
pub struct Bridge<'a> {
225225
/// Reusable buffer (only `clear`-ed, never shrunk), primarily
226226
/// used for making requests, but also for passing input to client.
227-
cached_buffer: Buffer<u8>,
227+
cached_buffer: Buffer,
228228

229229
/// Server-side function that the client uses to make requests.
230-
dispatch: closure::Closure<'a, Buffer<u8>, Buffer<u8>>,
230+
dispatch: closure::Closure<'a, Buffer, Buffer>,
231231

232232
/// If 'true', always invoke the default panic hook
233233
force_show_panics: bool,
234234

235-
// Prevent Send and Sync impls
235+
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
236+
// this, but that requires unstable features. rust-analyzer uses this code
237+
// and avoids unstable features.
236238
_marker: marker::PhantomData<*mut ()>,
237239
}
238240

@@ -252,7 +254,6 @@ mod api_tags {
252254
rpc_encode_decode!(enum $name { $($method),* });
253255
)*
254256

255-
256257
pub(super) enum Method {
257258
$($name($name)),*
258259
}

proc_macro/src/bridge/rpc.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::num::NonZeroU32;
77
use std::ops::Bound;
88
use std::str;
99

10-
pub(super) type Writer = super::buffer::Buffer<u8>;
10+
pub(super) type Writer = super::buffer::Buffer;
1111

1212
pub(super) trait Encode<S>: Sized {
1313
fn encode(self, w: &mut Writer, s: &mut S);

0 commit comments

Comments
 (0)