mirror of
https://github.com/rust-lang/rust.git
synced 2025-02-11 14:33:32 +00:00
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`
This commit is contained in:
commit
f558990814
@ -22,21 +22,16 @@ struct ProcMacroDerive {
|
||||
attrs: Vec<Symbol>,
|
||||
}
|
||||
|
||||
enum ProcMacroDefType {
|
||||
Attr,
|
||||
Bang,
|
||||
}
|
||||
|
||||
struct ProcMacroDef {
|
||||
id: NodeId,
|
||||
function_name: Ident,
|
||||
span: Span,
|
||||
def_type: ProcMacroDefType,
|
||||
}
|
||||
|
||||
enum ProcMacro {
|
||||
Derive(ProcMacroDerive),
|
||||
Def(ProcMacroDef),
|
||||
Attr(ProcMacroDef),
|
||||
Bang(ProcMacroDef),
|
||||
}
|
||||
|
||||
struct CollectProcMacros<'a> {
|
||||
@ -128,11 +123,10 @@ impl<'a> CollectProcMacros<'a> {
|
||||
|
||||
fn collect_attr_proc_macro(&mut self, item: &'a ast::Item) {
|
||||
if self.in_root && item.vis.kind.is_pub() {
|
||||
self.macros.push(ProcMacro::Def(ProcMacroDef {
|
||||
self.macros.push(ProcMacro::Attr(ProcMacroDef {
|
||||
id: item.id,
|
||||
span: item.span,
|
||||
function_name: item.ident,
|
||||
def_type: ProcMacroDefType::Attr,
|
||||
}));
|
||||
} else {
|
||||
let msg = if !self.in_root {
|
||||
@ -147,11 +141,10 @@ impl<'a> CollectProcMacros<'a> {
|
||||
|
||||
fn collect_bang_proc_macro(&mut self, item: &'a ast::Item) {
|
||||
if self.in_root && item.vis.kind.is_pub() {
|
||||
self.macros.push(ProcMacro::Def(ProcMacroDef {
|
||||
self.macros.push(ProcMacro::Bang(ProcMacroDef {
|
||||
id: item.id,
|
||||
span: item.span,
|
||||
function_name: item.ident,
|
||||
def_type: ProcMacroDefType::Bang,
|
||||
}));
|
||||
} else {
|
||||
let msg = if !self.in_root {
|
||||
@ -308,6 +301,17 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
|
||||
let proc_macro_ty_method_path = |cx: &ExtCtxt<'_>, method| {
|
||||
cx.expr_path(cx.path(span, vec![proc_macro, bridge, client, proc_macro_ty, method]))
|
||||
};
|
||||
let attr_or_bang = |cx: &mut ExtCtxt<'_>, ca: &ProcMacroDef, ident| {
|
||||
cx.resolver.declare_proc_macro(ca.id);
|
||||
cx.expr_call(
|
||||
span,
|
||||
proc_macro_ty_method_path(cx, ident),
|
||||
vec![
|
||||
cx.expr_str(ca.span, ca.function_name.name),
|
||||
local_path(cx, ca.span, ca.function_name),
|
||||
],
|
||||
)
|
||||
};
|
||||
macros
|
||||
.iter()
|
||||
.map(|m| match m {
|
||||
@ -329,22 +333,8 @@ fn mk_decls(cx: &mut ExtCtxt<'_>, macros: &[ProcMacro]) -> P<ast::Item> {
|
||||
],
|
||||
)
|
||||
}
|
||||
ProcMacro::Def(ca) => {
|
||||
cx.resolver.declare_proc_macro(ca.id);
|
||||
let ident = match ca.def_type {
|
||||
ProcMacroDefType::Attr => attr,
|
||||
ProcMacroDefType::Bang => bang,
|
||||
};
|
||||
|
||||
cx.expr_call(
|
||||
span,
|
||||
proc_macro_ty_method_path(cx, ident),
|
||||
vec![
|
||||
cx.expr_str(ca.span, ca.function_name.name),
|
||||
local_path(cx, ca.span, ca.function_name),
|
||||
],
|
||||
)
|
||||
}
|
||||
ProcMacro::Attr(ca) => attr_or_bang(cx, &ca, attr),
|
||||
ProcMacro::Bang(ca) => attr_or_bang(cx, &ca, bang),
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
|
@ -266,7 +266,7 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub trait ProcMacro {
|
||||
pub trait BangProcMacro {
|
||||
fn expand<'cx>(
|
||||
&self,
|
||||
ecx: &'cx mut ExtCtxt<'_>,
|
||||
@ -275,7 +275,7 @@ pub trait ProcMacro {
|
||||
) -> Result<TokenStream, ErrorGuaranteed>;
|
||||
}
|
||||
|
||||
impl<F> ProcMacro for F
|
||||
impl<F> BangProcMacro for F
|
||||
where
|
||||
F: Fn(TokenStream) -> TokenStream,
|
||||
{
|
||||
@ -640,7 +640,7 @@ pub enum SyntaxExtensionKind {
|
||||
/// A token-based function-like macro.
|
||||
Bang(
|
||||
/// An expander with signature TokenStream -> TokenStream.
|
||||
Box<dyn ProcMacro + sync::Sync + sync::Send>,
|
||||
Box<dyn BangProcMacro + sync::Sync + sync::Send>,
|
||||
),
|
||||
|
||||
/// An AST-based function-like macro.
|
||||
|
@ -17,7 +17,7 @@ pub struct BangProcMacro {
|
||||
pub client: pm::bridge::client::Client<fn(pm::TokenStream) -> pm::TokenStream>,
|
||||
}
|
||||
|
||||
impl base::ProcMacro for BangProcMacro {
|
||||
impl base::BangProcMacro for BangProcMacro {
|
||||
fn expand<'cx>(
|
||||
&self,
|
||||
ecx: &'cx mut ExtCtxt<'_>,
|
||||
@ -72,11 +72,11 @@ impl base::AttrProcMacro for AttrProcMacro {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ProcMacroDerive {
|
||||
pub struct DeriveProcMacro {
|
||||
pub client: pm::bridge::client::Client<fn(pm::TokenStream) -> pm::TokenStream>,
|
||||
}
|
||||
|
||||
impl MultiItemModifier for ProcMacroDerive {
|
||||
impl MultiItemModifier for DeriveProcMacro {
|
||||
fn expand(
|
||||
&self,
|
||||
ecx: &mut ExtCtxt<'_>,
|
||||
|
@ -11,7 +11,7 @@ use rustc_data_structures::svh::Svh;
|
||||
use rustc_data_structures::sync::{Lock, LockGuard, Lrc, OnceCell};
|
||||
use rustc_data_structures::unhash::UnhashMap;
|
||||
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
|
||||
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, ProcMacroDerive};
|
||||
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
|
||||
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
|
||||
use rustc_hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX, LOCAL_CRATE};
|
||||
use rustc_hir::definitions::{DefKey, DefPath, DefPathData, DefPathHash};
|
||||
@ -837,7 +837,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> {
|
||||
attributes.iter().cloned().map(Symbol::intern).collect::<Vec<_>>();
|
||||
(
|
||||
trait_name,
|
||||
SyntaxExtensionKind::Derive(Box::new(ProcMacroDerive { client })),
|
||||
SyntaxExtensionKind::Derive(Box::new(DeriveProcMacro { client })),
|
||||
helper_attrs,
|
||||
)
|
||||
}
|
||||
|
@ -6,37 +6,37 @@ use std::ops::{Deref, DerefMut};
|
||||
use std::slice;
|
||||
|
||||
#[repr(C)]
|
||||
pub struct Buffer<T: Copy> {
|
||||
data: *mut T,
|
||||
pub struct Buffer {
|
||||
data: *mut u8,
|
||||
len: usize,
|
||||
capacity: usize,
|
||||
reserve: extern "C" fn(Buffer<T>, usize) -> Buffer<T>,
|
||||
drop: extern "C" fn(Buffer<T>),
|
||||
reserve: extern "C" fn(Buffer, usize) -> Buffer,
|
||||
drop: extern "C" fn(Buffer),
|
||||
}
|
||||
|
||||
unsafe impl<T: Copy + Sync> Sync for Buffer<T> {}
|
||||
unsafe impl<T: Copy + Send> Send for Buffer<T> {}
|
||||
unsafe impl Sync for Buffer {}
|
||||
unsafe impl Send for Buffer {}
|
||||
|
||||
impl<T: Copy> Default for Buffer<T> {
|
||||
impl Default for Buffer {
|
||||
fn default() -> Self {
|
||||
Self::from(vec![])
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> Deref for Buffer<T> {
|
||||
type Target = [T];
|
||||
fn deref(&self) -> &[T] {
|
||||
unsafe { slice::from_raw_parts(self.data as *const T, self.len) }
|
||||
impl Deref for Buffer {
|
||||
type Target = [u8];
|
||||
fn deref(&self) -> &[u8] {
|
||||
unsafe { slice::from_raw_parts(self.data as *const u8, self.len) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> DerefMut for Buffer<T> {
|
||||
fn deref_mut(&mut self) -> &mut [T] {
|
||||
impl DerefMut for Buffer {
|
||||
fn deref_mut(&mut self) -> &mut [u8] {
|
||||
unsafe { slice::from_raw_parts_mut(self.data, self.len) }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> Buffer<T> {
|
||||
impl Buffer {
|
||||
pub(super) fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
@ -53,7 +53,7 @@ impl<T: Copy> Buffer<T> {
|
||||
// because in the case of small arrays, codegen can be more efficient
|
||||
// (avoiding a memmove call). With extend_from_slice, LLVM at least
|
||||
// currently is not able to make that optimization.
|
||||
pub(super) fn extend_from_array<const N: usize>(&mut self, xs: &[T; N]) {
|
||||
pub(super) fn extend_from_array<const N: usize>(&mut self, xs: &[u8; N]) {
|
||||
if xs.len() > (self.capacity - self.len) {
|
||||
let b = self.take();
|
||||
*self = (b.reserve)(b, xs.len());
|
||||
@ -64,7 +64,7 @@ impl<T: Copy> Buffer<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn extend_from_slice(&mut self, xs: &[T]) {
|
||||
pub(super) fn extend_from_slice(&mut self, xs: &[u8]) {
|
||||
if xs.len() > (self.capacity - self.len) {
|
||||
let b = self.take();
|
||||
*self = (b.reserve)(b, xs.len());
|
||||
@ -75,7 +75,7 @@ impl<T: Copy> Buffer<T> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn push(&mut self, v: T) {
|
||||
pub(super) fn push(&mut self, v: u8) {
|
||||
// The code here is taken from Vec::push, and we know that reserve()
|
||||
// will panic if we're exceeding isize::MAX bytes and so there's no need
|
||||
// to check for overflow.
|
||||
@ -90,7 +90,7 @@ impl<T: Copy> Buffer<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Write for Buffer<u8> {
|
||||
impl Write for Buffer {
|
||||
fn write(&mut self, xs: &[u8]) -> io::Result<usize> {
|
||||
self.extend_from_slice(xs);
|
||||
Ok(xs.len())
|
||||
@ -106,21 +106,21 @@ impl Write for Buffer<u8> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> Drop for Buffer<T> {
|
||||
impl Drop for Buffer {
|
||||
fn drop(&mut self) {
|
||||
let b = self.take();
|
||||
(b.drop)(b);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Copy> From<Vec<T>> for Buffer<T> {
|
||||
fn from(mut v: Vec<T>) -> Self {
|
||||
impl From<Vec<u8>> for Buffer {
|
||||
fn from(mut v: Vec<u8>) -> Self {
|
||||
let (data, len, capacity) = (v.as_mut_ptr(), v.len(), v.capacity());
|
||||
mem::forget(v);
|
||||
|
||||
// This utility function is nested in here because it can *only*
|
||||
// be safely called on `Buffer`s created by *this* `proc_macro`.
|
||||
fn to_vec<T: Copy>(b: Buffer<T>) -> Vec<T> {
|
||||
fn to_vec(b: Buffer) -> Vec<u8> {
|
||||
unsafe {
|
||||
let Buffer { data, len, capacity, .. } = b;
|
||||
mem::forget(b);
|
||||
@ -128,13 +128,13 @@ impl<T: Copy> From<Vec<T>> for Buffer<T> {
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn reserve<T: Copy>(b: Buffer<T>, additional: usize) -> Buffer<T> {
|
||||
extern "C" fn reserve(b: Buffer, additional: usize) -> Buffer {
|
||||
let mut v = to_vec(b);
|
||||
v.reserve(additional);
|
||||
Buffer::from(v)
|
||||
}
|
||||
|
||||
extern "C" fn drop<T: Copy>(b: Buffer<T>) {
|
||||
extern "C" fn drop(b: Buffer) {
|
||||
mem::drop(to_vec(b));
|
||||
}
|
||||
|
||||
|
@ -49,7 +49,9 @@ macro_rules! define_handles {
|
||||
#[repr(C)]
|
||||
pub(crate) struct $oty {
|
||||
handle: handle::Handle,
|
||||
// Prevent Send and Sync impls
|
||||
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual
|
||||
// way of doing this, but that requires unstable features.
|
||||
// rust-analyzer uses this code and avoids unstable features.
|
||||
_marker: PhantomData<*mut ()>,
|
||||
}
|
||||
|
||||
@ -133,7 +135,9 @@ macro_rules! define_handles {
|
||||
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
|
||||
pub(crate) struct $ity {
|
||||
handle: handle::Handle,
|
||||
// Prevent Send and Sync impls
|
||||
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual
|
||||
// way of doing this, but that requires unstable features.
|
||||
// rust-analyzer uses this code and avoids unstable features.
|
||||
_marker: PhantomData<*mut ()>,
|
||||
}
|
||||
|
||||
@ -191,7 +195,7 @@ define_handles! {
|
||||
// FIXME(eddyb) generate these impls by pattern-matching on the
|
||||
// names of methods - also could use the presence of `fn drop`
|
||||
// to distinguish between 'owned and 'interned, above.
|
||||
// Alternatively, special 'modes" could be listed of types in with_api
|
||||
// Alternatively, special "modes" could be listed of types in with_api
|
||||
// instead of pattern matching on methods, here and in server decl.
|
||||
|
||||
impl Clone for TokenStream {
|
||||
@ -250,17 +254,17 @@ macro_rules! define_client_side {
|
||||
$(impl $name {
|
||||
$(pub(crate) fn $method($($arg: $arg_ty),*) $(-> $ret_ty)* {
|
||||
Bridge::with(|bridge| {
|
||||
let mut b = bridge.cached_buffer.take();
|
||||
let mut buf = bridge.cached_buffer.take();
|
||||
|
||||
b.clear();
|
||||
api_tags::Method::$name(api_tags::$name::$method).encode(&mut b, &mut ());
|
||||
reverse_encode!(b; $($arg),*);
|
||||
buf.clear();
|
||||
api_tags::Method::$name(api_tags::$name::$method).encode(&mut buf, &mut ());
|
||||
reverse_encode!(buf; $($arg),*);
|
||||
|
||||
b = bridge.dispatch.call(b);
|
||||
buf = bridge.dispatch.call(buf);
|
||||
|
||||
let r = Result::<_, PanicMessage>::decode(&mut &b[..], &mut ());
|
||||
let r = Result::<_, PanicMessage>::decode(&mut &buf[..], &mut ());
|
||||
|
||||
bridge.cached_buffer = b;
|
||||
bridge.cached_buffer = buf;
|
||||
|
||||
r.unwrap_or_else(|e| panic::resume_unwind(e.into()))
|
||||
})
|
||||
@ -367,7 +371,7 @@ pub struct Client<F> {
|
||||
// FIXME(eddyb) use a reference to the `static COUNTERS`, instead of
|
||||
// a wrapper `fn` pointer, once `const fn` can reference `static`s.
|
||||
pub(super) get_handle_counters: extern "C" fn() -> &'static HandleCounters,
|
||||
pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer<u8>,
|
||||
pub(super) run: extern "C" fn(Bridge<'_>, F) -> Buffer,
|
||||
pub(super) f: F,
|
||||
}
|
||||
|
||||
@ -377,22 +381,22 @@ pub struct Client<F> {
|
||||
fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
|
||||
mut bridge: Bridge<'_>,
|
||||
f: impl FnOnce(A) -> R,
|
||||
) -> Buffer<u8> {
|
||||
) -> Buffer {
|
||||
// The initial `cached_buffer` contains the input.
|
||||
let mut b = bridge.cached_buffer.take();
|
||||
let mut buf = bridge.cached_buffer.take();
|
||||
|
||||
panic::catch_unwind(panic::AssertUnwindSafe(|| {
|
||||
bridge.enter(|| {
|
||||
let reader = &mut &b[..];
|
||||
let reader = &mut &buf[..];
|
||||
let input = A::decode(reader, &mut ());
|
||||
|
||||
// Put the `cached_buffer` back in the `Bridge`, for requests.
|
||||
Bridge::with(|bridge| bridge.cached_buffer = b.take());
|
||||
Bridge::with(|bridge| bridge.cached_buffer = buf.take());
|
||||
|
||||
let output = f(input);
|
||||
|
||||
// Take the `cached_buffer` back out, for the output value.
|
||||
b = Bridge::with(|bridge| bridge.cached_buffer.take());
|
||||
buf = Bridge::with(|bridge| bridge.cached_buffer.take());
|
||||
|
||||
// HACK(eddyb) Separate encoding a success value (`Ok(output)`)
|
||||
// from encoding a panic (`Err(e: PanicMessage)`) to avoid
|
||||
@ -403,16 +407,16 @@ fn run_client<A: for<'a, 's> DecodeMut<'a, 's, ()>, R: Encode<()>>(
|
||||
// this is defensively trying to avoid any accidental panicking
|
||||
// reaching the `extern "C"` (which should `abort` but might not
|
||||
// at the moment, so this is also potentially preventing UB).
|
||||
b.clear();
|
||||
Ok::<_, ()>(output).encode(&mut b, &mut ());
|
||||
buf.clear();
|
||||
Ok::<_, ()>(output).encode(&mut buf, &mut ());
|
||||
})
|
||||
}))
|
||||
.map_err(PanicMessage::from)
|
||||
.unwrap_or_else(|e| {
|
||||
b.clear();
|
||||
Err::<(), _>(e).encode(&mut b, &mut ());
|
||||
buf.clear();
|
||||
Err::<(), _>(e).encode(&mut buf, &mut ());
|
||||
});
|
||||
b
|
||||
buf
|
||||
}
|
||||
|
||||
impl Client<fn(crate::TokenStream) -> crate::TokenStream> {
|
||||
@ -420,7 +424,7 @@ impl Client<fn(crate::TokenStream) -> crate::TokenStream> {
|
||||
extern "C" fn run(
|
||||
bridge: Bridge<'_>,
|
||||
f: impl FnOnce(crate::TokenStream) -> crate::TokenStream,
|
||||
) -> Buffer<u8> {
|
||||
) -> Buffer {
|
||||
run_client(bridge, |input| f(crate::TokenStream(input)).0)
|
||||
}
|
||||
Client { get_handle_counters: HandleCounters::get, run, f }
|
||||
@ -434,7 +438,7 @@ impl Client<fn(crate::TokenStream, crate::TokenStream) -> crate::TokenStream> {
|
||||
extern "C" fn run(
|
||||
bridge: Bridge<'_>,
|
||||
f: impl FnOnce(crate::TokenStream, crate::TokenStream) -> crate::TokenStream,
|
||||
) -> Buffer<u8> {
|
||||
) -> Buffer {
|
||||
run_client(bridge, |(input, input2)| {
|
||||
f(crate::TokenStream(input), crate::TokenStream(input2)).0
|
||||
})
|
||||
|
@ -6,7 +6,11 @@ use std::marker::PhantomData;
|
||||
pub struct Closure<'a, A, R> {
|
||||
call: unsafe extern "C" fn(*mut Env, A) -> R,
|
||||
env: *mut Env,
|
||||
// Ensure Closure is !Send and !Sync
|
||||
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
|
||||
// this, but that requires unstable features. rust-analyzer uses this code
|
||||
// and avoids unstable features.
|
||||
//
|
||||
// The `'a` lifetime parameter represents the lifetime of `Env`.
|
||||
_marker: PhantomData<*mut &'a mut ()>,
|
||||
}
|
||||
|
||||
|
@ -8,6 +8,8 @@ use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
pub(super) type Handle = NonZeroU32;
|
||||
|
||||
/// A store that associates values of type `T` with numeric handles. A value can
|
||||
/// be looked up using its handle.
|
||||
pub(super) struct OwnedStore<T: 'static> {
|
||||
counter: &'static AtomicUsize,
|
||||
data: BTreeMap<Handle, T>,
|
||||
@ -49,6 +51,7 @@ impl<T> IndexMut<Handle> for OwnedStore<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like `OwnedStore`, but avoids storing any value more than once.
|
||||
pub(super) struct InternedStore<T: 'static> {
|
||||
owned: OwnedStore<T>,
|
||||
interner: HashMap<T, Handle>,
|
||||
|
@ -176,7 +176,7 @@ macro_rules! with_api {
|
||||
}
|
||||
|
||||
// FIXME(eddyb) this calls `encode` for each argument, but in reverse,
|
||||
// to avoid borrow conflicts from borrows started by `&mut` arguments.
|
||||
// to match the ordering in `reverse_decode`.
|
||||
macro_rules! reverse_encode {
|
||||
($writer:ident;) => {};
|
||||
($writer:ident; $first:ident $(, $rest:ident)*) => {
|
||||
@ -224,15 +224,17 @@ use rpc::{Decode, DecodeMut, Encode, Reader, Writer};
|
||||
pub struct Bridge<'a> {
|
||||
/// Reusable buffer (only `clear`-ed, never shrunk), primarily
|
||||
/// used for making requests, but also for passing input to client.
|
||||
cached_buffer: Buffer<u8>,
|
||||
cached_buffer: Buffer,
|
||||
|
||||
/// Server-side function that the client uses to make requests.
|
||||
dispatch: closure::Closure<'a, Buffer<u8>, Buffer<u8>>,
|
||||
dispatch: closure::Closure<'a, Buffer, Buffer>,
|
||||
|
||||
/// If 'true', always invoke the default panic hook
|
||||
force_show_panics: bool,
|
||||
|
||||
// Prevent Send and Sync impls
|
||||
// Prevent Send and Sync impls. `!Send`/`!Sync` is the usual way of doing
|
||||
// this, but that requires unstable features. rust-analyzer uses this code
|
||||
// and avoids unstable features.
|
||||
_marker: marker::PhantomData<*mut ()>,
|
||||
}
|
||||
|
||||
@ -252,7 +254,6 @@ mod api_tags {
|
||||
rpc_encode_decode!(enum $name { $($method),* });
|
||||
)*
|
||||
|
||||
|
||||
pub(super) enum Method {
|
||||
$($name($name)),*
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ use std::num::NonZeroU32;
|
||||
use std::ops::Bound;
|
||||
use std::str;
|
||||
|
||||
pub(super) type Writer = super::buffer::Buffer<u8>;
|
||||
pub(super) type Writer = super::buffer::Buffer;
|
||||
|
||||
pub(super) trait Encode<S>: Sized {
|
||||
fn encode(self, w: &mut Writer, s: &mut S);
|
||||
|
@ -5,37 +5,30 @@ use super::*;
|
||||
// FIXME(eddyb) generate the definition of `HandleStore` in `server.rs`.
|
||||
use super::client::HandleStore;
|
||||
|
||||
/// Declare an associated item of one of the traits below, optionally
|
||||
/// adjusting it (i.e., adding bounds to types and default bodies to methods).
|
||||
macro_rules! associated_item {
|
||||
(type FreeFunctions) =>
|
||||
(type FreeFunctions: 'static;);
|
||||
(type TokenStream) =>
|
||||
(type TokenStream: 'static + Clone;);
|
||||
(type TokenStreamBuilder) =>
|
||||
(type TokenStreamBuilder: 'static;);
|
||||
(type TokenStreamIter) =>
|
||||
(type TokenStreamIter: 'static + Clone;);
|
||||
(type Group) =>
|
||||
(type Group: 'static + Clone;);
|
||||
(type Punct) =>
|
||||
(type Punct: 'static + Copy + Eq + Hash;);
|
||||
(type Ident) =>
|
||||
(type Ident: 'static + Copy + Eq + Hash;);
|
||||
(type Literal) =>
|
||||
(type Literal: 'static + Clone;);
|
||||
(type SourceFile) =>
|
||||
(type SourceFile: 'static + Clone;);
|
||||
(type MultiSpan) =>
|
||||
(type MultiSpan: 'static;);
|
||||
(type Diagnostic) =>
|
||||
(type Diagnostic: 'static;);
|
||||
(type Span) =>
|
||||
(type Span: 'static + Copy + Eq + Hash;);
|
||||
pub trait Types {
|
||||
type FreeFunctions: 'static;
|
||||
type TokenStream: 'static + Clone;
|
||||
type TokenStreamBuilder: 'static;
|
||||
type TokenStreamIter: 'static + Clone;
|
||||
type Group: 'static + Clone;
|
||||
type Punct: 'static + Copy + Eq + Hash;
|
||||
type Ident: 'static + Copy + Eq + Hash;
|
||||
type Literal: 'static + Clone;
|
||||
type SourceFile: 'static + Clone;
|
||||
type MultiSpan: 'static;
|
||||
type Diagnostic: 'static;
|
||||
type Span: 'static + Copy + Eq + Hash;
|
||||
}
|
||||
|
||||
/// Declare an associated fn of one of the traits below, adding necessary
|
||||
/// default bodies.
|
||||
macro_rules! associated_fn {
|
||||
(fn drop(&mut self, $arg:ident: $arg_ty:ty)) =>
|
||||
(fn drop(&mut self, $arg: $arg_ty) { mem::drop($arg) });
|
||||
|
||||
(fn clone(&mut self, $arg:ident: $arg_ty:ty) -> $ret_ty:ty) =>
|
||||
(fn clone(&mut self, $arg: $arg_ty) -> $ret_ty { $arg.clone() });
|
||||
|
||||
($($item:tt)*) => ($($item)*;)
|
||||
}
|
||||
|
||||
@ -43,12 +36,8 @@ macro_rules! declare_server_traits {
|
||||
($($name:ident {
|
||||
$(fn $method:ident($($arg:ident: $arg_ty:ty),* $(,)?) $(-> $ret_ty:ty)?;)*
|
||||
}),* $(,)?) => {
|
||||
pub trait Types {
|
||||
$(associated_item!(type $name);)*
|
||||
}
|
||||
|
||||
$(pub trait $name: Types {
|
||||
$(associated_item!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
|
||||
$(associated_fn!(fn $method(&mut self, $($arg: $arg_ty),*) $(-> $ret_ty)?);)*
|
||||
})*
|
||||
|
||||
pub trait Server: Types $(+ $name)* {}
|
||||
@ -89,15 +78,15 @@ macro_rules! define_dispatcher_impl {
|
||||
pub trait DispatcherTrait {
|
||||
// HACK(eddyb) these are here to allow `Self::$name` to work below.
|
||||
$(type $name;)*
|
||||
fn dispatch(&mut self, b: Buffer<u8>) -> Buffer<u8>;
|
||||
fn dispatch(&mut self, buf: Buffer) -> Buffer;
|
||||
}
|
||||
|
||||
impl<S: Server> DispatcherTrait for Dispatcher<MarkedTypes<S>> {
|
||||
$(type $name = <MarkedTypes<S> as Types>::$name;)*
|
||||
fn dispatch(&mut self, mut b: Buffer<u8>) -> Buffer<u8> {
|
||||
fn dispatch(&mut self, mut buf: Buffer) -> Buffer {
|
||||
let Dispatcher { handle_store, server } = self;
|
||||
|
||||
let mut reader = &b[..];
|
||||
let mut reader = &buf[..];
|
||||
match api_tags::Method::decode(&mut reader, &mut ()) {
|
||||
$(api_tags::Method::$name(m) => match m {
|
||||
$(api_tags::$name::$method => {
|
||||
@ -116,12 +105,12 @@ macro_rules! define_dispatcher_impl {
|
||||
.map_err(PanicMessage::from)
|
||||
};
|
||||
|
||||
b.clear();
|
||||
r.encode(&mut b, handle_store);
|
||||
buf.clear();
|
||||
r.encode(&mut buf, handle_store);
|
||||
})*
|
||||
}),*
|
||||
}
|
||||
b
|
||||
buf
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -132,11 +121,11 @@ pub trait ExecutionStrategy {
|
||||
fn run_bridge_and_client<D: Copy + Send + 'static>(
|
||||
&self,
|
||||
dispatcher: &mut impl DispatcherTrait,
|
||||
input: Buffer<u8>,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
|
||||
input: Buffer,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
|
||||
client_data: D,
|
||||
force_show_panics: bool,
|
||||
) -> Buffer<u8>;
|
||||
) -> Buffer;
|
||||
}
|
||||
|
||||
pub struct SameThread;
|
||||
@ -145,12 +134,12 @@ impl ExecutionStrategy for SameThread {
|
||||
fn run_bridge_and_client<D: Copy + Send + 'static>(
|
||||
&self,
|
||||
dispatcher: &mut impl DispatcherTrait,
|
||||
input: Buffer<u8>,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
|
||||
input: Buffer,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
|
||||
client_data: D,
|
||||
force_show_panics: bool,
|
||||
) -> Buffer<u8> {
|
||||
let mut dispatch = |b| dispatcher.dispatch(b);
|
||||
) -> Buffer {
|
||||
let mut dispatch = |buf| dispatcher.dispatch(buf);
|
||||
|
||||
run_client(
|
||||
Bridge {
|
||||
@ -173,19 +162,19 @@ impl ExecutionStrategy for CrossThread1 {
|
||||
fn run_bridge_and_client<D: Copy + Send + 'static>(
|
||||
&self,
|
||||
dispatcher: &mut impl DispatcherTrait,
|
||||
input: Buffer<u8>,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
|
||||
input: Buffer,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
|
||||
client_data: D,
|
||||
force_show_panics: bool,
|
||||
) -> Buffer<u8> {
|
||||
) -> Buffer {
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
let (req_tx, req_rx) = channel();
|
||||
let (res_tx, res_rx) = channel();
|
||||
|
||||
let join_handle = thread::spawn(move || {
|
||||
let mut dispatch = |b| {
|
||||
req_tx.send(b).unwrap();
|
||||
let mut dispatch = |buf| {
|
||||
req_tx.send(buf).unwrap();
|
||||
res_rx.recv().unwrap()
|
||||
};
|
||||
|
||||
@ -214,11 +203,11 @@ impl ExecutionStrategy for CrossThread2 {
|
||||
fn run_bridge_and_client<D: Copy + Send + 'static>(
|
||||
&self,
|
||||
dispatcher: &mut impl DispatcherTrait,
|
||||
input: Buffer<u8>,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
|
||||
input: Buffer,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
|
||||
client_data: D,
|
||||
force_show_panics: bool,
|
||||
) -> Buffer<u8> {
|
||||
) -> Buffer {
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
enum State<T> {
|
||||
@ -285,25 +274,25 @@ fn run_server<
|
||||
handle_counters: &'static client::HandleCounters,
|
||||
server: S,
|
||||
input: I,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer<u8>,
|
||||
run_client: extern "C" fn(Bridge<'_>, D) -> Buffer,
|
||||
client_data: D,
|
||||
force_show_panics: bool,
|
||||
) -> Result<O, PanicMessage> {
|
||||
let mut dispatcher =
|
||||
Dispatcher { handle_store: HandleStore::new(handle_counters), server: MarkedTypes(server) };
|
||||
|
||||
let mut b = Buffer::new();
|
||||
input.encode(&mut b, &mut dispatcher.handle_store);
|
||||
let mut buf = Buffer::new();
|
||||
input.encode(&mut buf, &mut dispatcher.handle_store);
|
||||
|
||||
b = strategy.run_bridge_and_client(
|
||||
buf = strategy.run_bridge_and_client(
|
||||
&mut dispatcher,
|
||||
b,
|
||||
buf,
|
||||
run_client,
|
||||
client_data,
|
||||
force_show_panics,
|
||||
);
|
||||
|
||||
Result::decode(&mut &b[..], &mut dispatcher.handle_store)
|
||||
Result::decode(&mut &buf[..], &mut dispatcher.handle_store)
|
||||
}
|
||||
|
||||
impl client::Client<fn(crate::TokenStream) -> crate::TokenStream> {
|
||||
|
Loading…
Reference in New Issue
Block a user