Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f558990

Browse files
committedMay 27, 2022
Auto merge of #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 9a42c65 + 41c10dd commit f558990

File tree

11 files changed

+139
-148
lines changed

11 files changed

+139
-148
lines changed
 

‎compiler/rustc_builtin_macros/src/proc_macro_harness.rs

Lines changed: 17 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -22,21 +22,16 @@ struct ProcMacroDerive {
2222
attrs: Vec<Symbol>,
2323
}
2424

25-
enum ProcMacroDefType {
26-
Attr,
27-
Bang,
28-
}
29-
3025
struct ProcMacroDef {
3126
id: NodeId,
3227
function_name: Ident,
3328
span: Span,
34-
def_type: ProcMacroDefType,
3529
}
3630

3731
enum ProcMacro {
3832
Derive(ProcMacroDerive),
39-
Def(ProcMacroDef),
33+
Attr(ProcMacroDef),
34+
Bang(ProcMacroDef),
4035
}
4136

4237
struct CollectProcMacros<'a> {
@@ -128,11 +123,10 @@ impl<'a> CollectProcMacros<'a> {
128123

129124
fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
130125
if self.in_root && item.vis.kind.is_pub() {
131-
self.macros.push(ProcMacro::Def(ProcMacroDef {
126+
self.macros.push(ProcMacro::Attr(ProcMacroDef {
132127
id: item.id,
133128
span: item.span,
134129
function_name: item.ident,
135-
def_type: ProcMacroDefType::Attr,
136130
}));
137131
} else {
138132
let msg = if !self.in_root {
@@ -147,11 +141,10 @@ impl<'a> CollectProcMacros<'a> {
147141

148142
fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
149143
if self.in_root && item.vis.kind.is_pub() {
150-
self.macros.push(ProcMacro::Def(ProcMacroDef {
144+
self.macros.push(ProcMacro::Bang(ProcMacroDef {
151145
id: item.id,
152146
span: item.span,
153147
function_name: item.ident,
154-
def_type: ProcMacroDefType::Bang,
155148
}));
156149
} else {
157150
let msg = if !self.in_root {
@@ -308,6 +301,17 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
308301
let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| {
309302
cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method]))
310303
};
304+
let attr_or_bang = |cx: &mut ExtCtxt<'_>, ca: &ProcMacroDef, ident| {
305+
cx.resolver.declare_proc_macro(ca.id);
306+
cx.expr_call(
307+
span,
308+
proc_macro_ty_method_path(cx, ident),
309+
vec![
310+
cx.expr_str(ca.span, ca.function_name.name),
311+
local_path(cx, ca.span, ca.function_name),
312+
],
313+
)
314+
};
311315
macros
312316
.iter()
313317
.map(|m| match m {
@@ -329,22 +333,8 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
329333
],
330334
)
331335
}
332-
ProcMacro::Def(ca) => {
333-
cx.resolver.declare_proc_macro(ca.id);
334-
let ident = match ca.def_type {
335-
ProcMacroDefType::Attr => attr,
336-
ProcMacroDefType::Bang => bang,
337-
};
338-
339-
cx.expr_call(
340-
span,
341-
proc_macro_ty_method_path(cx, ident),
342-
vec![
343-
cx.expr_str(ca.span, ca.function_name.name),
344-
local_path(cx, ca.span, ca.function_name),
345-
],
346-
)
347-
}
336+
ProcMacro::Attr(ca) => attr_or_bang(cx, &ca, attr),
337+
ProcMacro::Bang(ca) => attr_or_bang(cx, &ca, bang),
348338
})
349339
.collect()
350340
};

‎compiler/rustc_expand/src/base.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ where
266266
}
267267
}
268268

269-
pub trait ProcMacro {
269+
pub trait BangProcMacro {
270270
fn expand<'cx>(
271271
&self,
272272
ecx: &'cx mut ExtCtxt<'_>,
@@ -275,7 +275,7 @@ pub trait ProcMacro {
275275
) -> Result<TokenStream, ErrorGuaranteed>;
276276
}
277277

278-
impl<F> ProcMacro for F
278+
impl<F> BangProcMacro for F
279279
where
280280
F: Fn(TokenStream) -> TokenStream,
281281
{
@@ -640,7 +640,7 @@ pub enum SyntaxExtensionKind {
640640
/// A token-based function-like macro.
641641
Bang(
642642
/// An expander with signature TokenStream -> TokenStream.
643-
Box<dyn ProcMacro + sync::Sync + sync::Send>,
643+
Box<dyn BangProcMacro + sync::Sync + sync::Send>,
644644
),
645645

646646
/// An AST-based function-like macro.

‎compiler/rustc_expand/src/proc_macro.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ pub struct BangProcMacro {
1717
pub client: pm::bridge::client::Client<fn(pm::TokenStream) -> pm::TokenStream>,
1818
}
1919

20-
impl base::ProcMacro for BangProcMacro {
20+
impl base::BangProcMacro for BangProcMacro {
2121
fn expand<'cx>(
2222
&self,
2323
ecx: &'cx mut ExtCtxt<'_>,
@@ -72,11 +72,11 @@ impl base::AttrProcMacro for AttrProcMacro {
7272
}
7373
}
7474

75-
pub struct ProcMacroDerive {
75+
pub struct DeriveProcMacro {
7676
pub client: pm::bridge::client::Client<fn(pm::TokenStream) -> pm::TokenStream>,
7777
}
7878

79-
impl MultiItemModifier for ProcMacroDerive {
79+
impl MultiItemModifier for DeriveProcMacro {
8080
fn expand(
8181
&self,
8282
ecx: &mut ExtCtxt<'_>,

‎compiler/rustc_metadata/src/rmeta/decoder.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use rustc_data_structures::svh::Svh;
1111
use rustc_data_structures::sync::{Lock, LockGuard, Lrc, OnceCell};
1212
use rustc_data_structures::unhash::UnhashMap;
1313
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
14-
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
14+
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
1515
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
1616
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
1717
use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
@@ -837,7 +837,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
837837
attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
838838
(
839839
trait_name,
840-
SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
840+
SyntaxExtensionKind::Derive(Box::new(DeriveProcMacro { client })),
841841
helper_attrs,
842842
)
843843
}

‎library/proc_macro/src/bridge/buffer.rs

Lines changed: 24 additions & 24 deletions
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

‎library/proc_macro/src/bridge/client.rs

Lines changed: 27 additions & 23 deletions
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
})

‎library/proc_macro/src/bridge/closure.rs

Lines changed: 5 additions & 1 deletion
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

‎library/proc_macro/src/bridge/handle.rs

Lines changed: 3 additions & 0 deletions
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>,

‎library/proc_macro/src/bridge/mod.rs

Lines changed: 6 additions & 5 deletions
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
}

‎library/proc_macro/src/bridge/rpc.rs

Lines changed: 1 addition & 1 deletion
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);

‎library/proc_macro/src/bridge/server.rs

Lines changed: 48 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -5,50 +5,39 @@ use super::*;
55
// FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
66
use super::client::HandleStore;
77

8-
/// Declare an associated item of one of the traits below, optionally
9-
/// adjusting it (i.e., adding bounds to types and default bodies to methods).
10-
macro_rules! associated_item {
11-
(type FreeFunctions) =>
12-
(type FreeFunctions: 'static;);
13-
(type TokenStream) =>
14-
(type TokenStream: 'static + Clone;);
15-
(type TokenStreamBuilder) =>
16-
(type TokenStreamBuilder: 'static;);
17-
(type TokenStreamIter) =>
18-
(type TokenStreamIter: 'static + Clone;);
19-
(type Group) =>
20-
(type Group: 'static + Clone;);
21-
(type Punct) =>
22-
(type Punct: 'static + Copy + Eq + Hash;);
23-
(type Ident) =>
24-
(type Ident: 'static + Copy + Eq + Hash;);
25-
(type Literal) =>
26-
(type Literal: 'static + Clone;);
27-
(type SourceFile) =>
28-
(type SourceFile: 'static + Clone;);
29-
(type MultiSpan) =>
30-
(type MultiSpan: 'static;);
31-
(type Diagnostic) =>
32-
(type Diagnostic: 'static;);
33-
(type Span) =>
34-
(type Span: 'static + Copy + Eq + Hash;);
8+
pub trait Types {
9+
type FreeFunctions: 'static;
10+
type TokenStream: 'static + Clone;
11+
type TokenStreamBuilder: 'static;
12+
type TokenStreamIter: 'static + Clone;
13+
type Group: 'static + Clone;
14+
type Punct: 'static + Copy + Eq + Hash;
15+
type Ident: 'static + Copy + Eq + Hash;
16+
type Literal: 'static + Clone;
17+
type SourceFile: 'static + Clone;
18+
type MultiSpan: 'static;
19+
type Diagnostic: 'static;
20+
type Span: 'static + Copy + Eq + Hash;
21+
}
22+
23+
/// Declare an associated fn of one of the traits below, adding necessary
24+
/// default bodies.
25+
macro_rules! associated_fn {
3526
(fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
3627
(fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
28+
3729
(fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
3830
(fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
31+
3932
($($item:tt)*) => ($($item)*;)
4033
}
4134

4235
macro_rules! declare_server_traits {
4336
($($name:ident {
4437
$(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
4538
}),* $(,)?) => {
46-
pub trait Types {
47-
$(associated_item!(type $name);)*
48-
}
49-
5039
$(pub trait $name: Types {
51-
$(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
40+
$(associated_fn!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
5241
})*
5342

5443
pub trait Server: Types $(+ $name)* {}
@@ -89,15 +78,15 @@ macro_rules! define_dispatcher_impl {
8978
pub trait DispatcherTrait {
9079
// HACK(eddyb) these are here to allow `Self::$name` to work below.
9180
$(type $name;)*
92-
fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
81+
fn dispatch(&mut self, buf: Buffer) -> Buffer;
9382
}
9483

9584
impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
9685
$(type $name = <MarkedTypes<S> as Types>::$name;)*
97-
fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
86+
fn dispatch(&mut self, mut buf: Buffer) -> Buffer {
9887
let Dispatcher { handle_store, server } = self;
9988

100-
let mut reader = &b[..];
89+
let mut reader = &buf[..];
10190
match api_tags::Method::decode(&mut reader, &mut ()) {
10291
$(api_tags::Method::$name(m) => match m {
10392
$(api_tags::$name::$method => {
@@ -116,12 +105,12 @@ macro_rules! define_dispatcher_impl {
116105
.map_err(PanicMessage::from)
117106
};
118107

119-
b.clear();
120-
r.encode(&mut b, handle_store);
108+
buf.clear();
109+
r.encode(&mut buf, handle_store);
121110
})*
122111
}),*
123112
}
124-
b
113+
buf
125114
}
126115
}
127116
}
@@ -132,11 +121,11 @@ pub trait ExecutionStrategy {
132121
fn run_bridge_and_client<D: Copy + Send + 'static>(
133122
&self,
134123
dispatcher: &mut impl DispatcherTrait,
135-
input: Buffer<u8>,
136-
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
124+
input: Buffer,
125+
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
137126
client_data: D,
138127
force_show_panics: bool,
139-
) -> Buffer<u8>;
128+
) -> Buffer;
140129
}
141130

142131
pub struct SameThread;
@@ -145,12 +134,12 @@ impl ExecutionStrategy for SameThread {
145134
fn run_bridge_and_client<D: Copy + Send + 'static>(
146135
&self,
147136
dispatcher: &mut impl DispatcherTrait,
148-
input: Buffer<u8>,
149-
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
137+
input: Buffer,
138+
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
150139
client_data: D,
151140
force_show_panics: bool,
152-
) -> Buffer<u8> {
153-
let mut dispatch = |b| dispatcher.dispatch(b);
141+
) -> Buffer {
142+
let mut dispatch = |buf| dispatcher.dispatch(buf);
154143

155144
run_client(
156145
Bridge {
@@ -173,19 +162,19 @@ impl ExecutionStrategy for CrossThread1 {
173162
fn run_bridge_and_client<D: Copy + Send + 'static>(
174163
&self,
175164
dispatcher: &mut impl DispatcherTrait,
176-
input: Buffer<u8>,
177-
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
165+
input: Buffer,
166+
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
178167
client_data: D,
179168
force_show_panics: bool,
180-
) -> Buffer<u8> {
169+
) -> Buffer {
181170
use std::sync::mpsc::channel;
182171

183172
let (req_tx, req_rx) = channel();
184173
let (res_tx, res_rx) = channel();
185174

186175
let join_handle = thread::spawn(move || {
187-
let mut dispatch = |b| {
188-
req_tx.send(b).unwrap();
176+
let mut dispatch = |buf| {
177+
req_tx.send(buf).unwrap();
189178
res_rx.recv().unwrap()
190179
};
191180

@@ -214,11 +203,11 @@ impl ExecutionStrategy for CrossThread2 {
214203
fn run_bridge_and_client<D: Copy + Send + 'static>(
215204
&self,
216205
dispatcher: &mut impl DispatcherTrait,
217-
input: Buffer<u8>,
218-
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
206+
input: Buffer,
207+
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
219208
client_data: D,
220209
force_show_panics: bool,
221-
) -> Buffer<u8> {
210+
) -> Buffer {
222211
use std::sync::{Arc, Mutex};
223212

224213
enum State<T> {
@@ -285,25 +274,25 @@ fn run_server<
285274
handle_counters: &'static client::HandleCounters,
286275
server: S,
287276
input: I,
288-
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
277+
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
289278
client_data: D,
290279
force_show_panics: bool,
291280
) -> Result<O, PanicMessage> {
292281
let mut dispatcher =
293282
Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
294283

295-
let mut b = Buffer::new();
296-
input.encode(&mut b, &mut dispatcher.handle_store);
284+
let mut buf = Buffer::new();
285+
input.encode(&mut buf, &mut dispatcher.handle_store);
297286

298-
b = strategy.run_bridge_and_client(
287+
buf = strategy.run_bridge_and_client(
299288
&mut dispatcher,
300-
b,
289+
buf,
301290
run_client,
302291
client_data,
303292
force_show_panics,
304293
);
305294

306-
Result::decode(&mut &b[..], &mut dispatcher.handle_store)
295+
Result::decode(&mut &buf[..], &mut dispatcher.handle_store)
307296
}
308297

309298
impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {

0 commit comments

Comments
 (0)
Please sign in to comment.