1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
//! This crate removes some boilerplate for structs that simply delegate
//! some of their methods to one or more of their fields.
//!
//! It gives you the `delegate!` macro, which delegates method calls to selected
//! expressions (usually inner fields).
//!
//! ## Features:
//! - Delegate to a method with a different name
//! ```rust
//! use delegate::delegate;
//!
//! struct Stack {
//! inner: Vec<u32>,
//! }
//! impl Stack {
//! delegate! {
//! to self.inner {
//! #[call(push)]
//! pub fn add(&mut self, value: u32);
//! }
//! }
//! }
//! ```
//! - Use an arbitrary inner field expression
//! ```rust
//! use delegate::delegate;
//! use std::{cell::RefCell, ops::Deref, rc::Rc};
//!
//! struct Wrapper {
//! inner: Rc<RefCell<Vec<u32>>>,
//! }
//! impl Wrapper {
//! delegate! {
//! to self.inner.deref().borrow_mut() {
//! pub fn push(&mut self, val: u32);
//! }
//! }
//! }
//! ```
//! - Change the return type of the delegated method using a `From` impl or omit
//! it altogether
//! ```rust
//! use delegate::delegate;
//! use std::convert as delegate_convert;
//!
//! struct Inner;
//! impl Inner {
//! pub fn method(&self, num: u32) -> u32 { num }
//! }
//! struct Wrapper {
//! inner: Inner,
//! }
//! impl Wrapper {
//! delegate! {
//! to self.inner {
//! // calls method, converts result to u64
//! #[into]
//! pub fn method(&self, num: u32) -> u64;
//!
//! // calls method, returns ()
//! #[call(method)]
//! pub fn method_noreturn(&self, num: u32);
//! }
//! }
//! }
//! ```
//! - Delegate to multiple fields
//! ```rust
//! use delegate::delegate;
//!
//! struct MultiStack {
//! left: Vec<u32>,
//! right: Vec<u32>,
//! }
//! impl MultiStack {
//! delegate! {
//! to self.left {
//! ///! Push an item to the top of the left stack
//! #[call(push)]
//! pub fn push_left(&mut self, value: u32);
//! }
//! to self.right {
//! ///! Push an item to the top of the right stack
//! #[call(push)]
//! pub fn push_right(&mut self, value: u32);
//! }
//! }
//! }
//! ```
//! - Delegation of generic methods
//! - Inserts `#[inline(always)]` automatically (unless you specify `#[inline]`
//! manually on the method)
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::collections::HashMap;
use syn::{self, parse::ParseStream, spanned::Spanned, Error};
mod kw {
syn::custom_keyword!(to);
syn::custom_keyword!(target);
}
struct DelegatedMethod {
method: syn::TraitItemMethod,
attributes: Vec<syn::Attribute>,
visibility: syn::Visibility,
}
impl syn::parse::Parse for DelegatedMethod {
fn parse(input: ParseStream) -> Result<Self, Error> {
let attributes = input.call(syn::Attribute::parse_outer)?;
let visibility = input.call(syn::Visibility::parse)?;
Ok(DelegatedMethod {
method: input.parse()?,
attributes,
visibility,
})
}
}
struct DelegatedSegment {
delegator: syn::Expr,
methods: Vec<DelegatedMethod>,
}
impl syn::parse::Parse for DelegatedSegment {
fn parse(input: ParseStream) -> Result<Self, Error> {
if let Ok(keyword) = input.parse::<kw::target>() {
return Err(Error::new(keyword.span(), "You are using the old `target` expression, which is deprecated. Please replace `target` with `to`."));
} else {
input.parse::<kw::to>()?;
}
input.parse::<syn::Expr>().and_then(|delegator| {
let delegator = match delegator {
syn::Expr::Field(_) => delegator,
syn::Expr::MethodCall(_) => delegator,
syn::Expr::Call(_) => delegator,
syn::Expr::Group(group) => *group.expr,
_ => panic!("Use a field expression to select delegator (e.g. self.inner)"),
};
let content;
syn::braced!(content in input);
let mut methods = vec![];
while !content.is_empty() {
methods.push(content.parse::<DelegatedMethod>().unwrap());
}
Ok(DelegatedSegment { delegator, methods })
})
}
}
struct DelegationBlock {
segments: Vec<DelegatedSegment>,
}
impl syn::parse::Parse for DelegationBlock {
fn parse(input: ParseStream) -> Result<Self, Error> {
let mut segments = vec![];
while !input.is_empty() {
segments.push(input.parse()?);
}
Ok(DelegationBlock { segments })
}
}
struct CallMethodAttribute {
name: syn::Ident,
}
impl syn::parse::Parse for CallMethodAttribute {
fn parse(input: ParseStream) -> Result<Self, Error> {
let content;
syn::parenthesized!(content in input);
Ok(CallMethodAttribute {
name: content.parse()?,
})
}
}
/// Iterates through the attributes of a method and filters special attributes.
/// call => sets the name of the target method to call
/// into => generates a `into()` call for the returned value
///
/// Returns tuple (blackbox attributes, name, into)
fn parse_attributes<'a>(
attrs: &'a [syn::Attribute], method: &syn::TraitItemMethod,
) -> (Vec<&'a syn::Attribute>, Option<syn::Ident>, bool) {
let mut name: Option<syn::Ident> = None;
let mut into: Option<bool> = None;
let mut map: HashMap<&str, Box<dyn FnMut(TokenStream2) -> ()>> =
Default::default();
map.insert(
"call",
Box::new(|stream| {
let target = syn::parse2::<CallMethodAttribute>(stream).unwrap();
if name.is_some() {
panic!(
"Multiple call attributes specified for {}",
method.sig.ident
)
}
name = Some(target.name.clone());
}),
);
map.insert(
"target_method",
Box::new(|_| {
panic!("You are using the old `target_method` attribute, which is deprecated. Please replace `target_method` with `call`.");
}),
);
map.insert(
"into",
Box::new(|_| {
if into.is_some() {
panic!(
"Multiple into attributes specified for {}",
method.sig.ident
)
}
into = Some(true);
}),
);
let attrs: Vec<&syn::Attribute> = attrs
.iter()
.filter(|attr| {
if let syn::AttrStyle::Outer = attr.style {
for (ident, callback) in map.iter_mut() {
if attr.path.is_ident(ident) {
callback(attr.tokens.clone());
return false;
}
}
}
true
})
.collect();
drop(map);
(attrs, name, into.unwrap_or(true))
}
/// Returns true if there are any `inline` attributes in the input.
fn has_inline_attribute(attrs: &[&syn::Attribute]) -> bool {
attrs.iter().any(|attr| {
if let syn::AttrStyle::Outer = attr.style {
attr.path.is_ident("inline")
} else {
false
}
})
}
#[proc_macro]
pub fn delegate(tokens: TokenStream) -> TokenStream {
let block: DelegationBlock = syn::parse_macro_input!(tokens);
let sections = block.segments.iter().map(|delegator| {
let delegator_attribute = &delegator.delegator;
let functions = delegator.methods.iter().map(|method| {
let input = &method.method;
let signature = &input.sig;
let inputs = &input.sig.inputs;
let (attrs, name, into) = parse_attributes(&method.attributes, &input);
if input.default.is_some() {
panic!(
"Do not include implementation of delegated functions ({})",
signature.ident
);
}
let args: Vec<syn::Ident> = inputs
.iter()
.filter_map(|i| match i {
syn::FnArg::Typed(typed) => match &*typed.pat {
syn::Pat::Ident(ident) => {
if ident.ident == "self" {
None
} else {
Some(ident.ident.clone())
}
}
_ => panic!(
"You have to use simple identifiers for delegated method parameters ({})",
input.sig.ident
),
},
_ => None,
})
.collect();
let name = match &name {
Some(n) => &n,
None => &input.sig.ident
};
let inline = if has_inline_attribute(&attrs) {
quote!()
} else {
quote! { #[inline(always)] }
};
let visibility = &method.visibility;
let body = quote::quote! { #delegator_attribute.#name(#(#args),*) };
let span = input.span();
let body = match &signature.output {
syn::ReturnType::Default => quote::quote! { #body; },
syn::ReturnType::Type(_, ret_type) => {
if into {
quote::quote! { delegate_convert::Into::<#ret_type>::into(#body) }
}
else {
body
}
}
};
quote::quote_spanned! {span=>
#(#attrs)*
#inline
#visibility #signature {
#body
}
}
});
quote! { #(#functions)* }
});
let result = quote! {
#(#sections)*
};
result.into()
}