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
use proc_macro::TokenStream;
use quote::quote;
///Generates trait implementation for specified type, relying on `Deref` or `Into` depending on
///whether `self` is reference or owned
///
///Note that this crate is only needed due to lack of specialization that would allow to have
///generic implementation over `T: Deref<Target=O>`
///
///## Example
///
///```rust
///use auto_trait::auto_trait;
///pub struct Wrapper(u32);
///
///impl Into<u32> for Wrapper {
/// fn into(self) -> u32 {
/// self.0
/// }
///}
///
///impl core::ops::Deref for Wrapper {
/// type Target = u32;
/// fn deref(&self) -> &Self::Target {
/// &self.0
/// }
///}
///
///impl core::ops::DerefMut for Wrapper {
/// fn deref_mut(&mut self) -> &mut Self::Target {
/// &mut self.0
/// }
///}
///
///#[auto_trait(Wrapper)]
///pub trait Lolka3 {
///}
///
///impl Lolka3 for u32 {}
///
///#[auto_trait(Box<T: Lolka2>)]
///#[auto_trait(Wrapper)]
///pub trait Lolka2 {
/// fn lolka2_ref(&self) -> u32;
/// fn lolka2_mut(&mut self) -> u32;
///}
///
///impl Lolka2 for u32 {
/// fn lolka2_ref(&self) -> u32 {
/// 10
/// }
/// fn lolka2_mut(&mut self) -> u32 {
/// 11
/// }
///}
///
///#[auto_trait(Box<T: Lolka + From<Box<T>>>)]
///pub trait Lolka {
/// fn lolka() -> u32;
///
/// fn lolka_ref(&self) -> u32;
///
/// fn lolka_mut(&mut self) -> u32;
///
/// fn lolka_self(self) -> u32;
///}
///
///impl Lolka for u32 {
/// fn lolka() -> u32 {
/// 1
/// }
///
/// fn lolka_ref(&self) -> u32 {
/// 2
/// }
///
/// fn lolka_mut(&mut self) -> u32 {
/// 3
/// }
///
/// fn lolka_self(self) -> u32 {
/// 4
/// }
///
///}
///
///let mut lolka = 0u32;
///let mut wrapped = Box::new(lolka);
///
///assert_eq!(lolka.lolka_ref(), wrapped.lolka_ref());
///assert_eq!(lolka.lolka_mut(), wrapped.lolka_mut());
///assert_eq!(lolka.lolka_self(), wrapped.lolka_self());
///
///assert_eq!(lolka.lolka2_ref(), wrapped.lolka2_ref());
///assert_eq!(lolka.lolka2_mut(), wrapped.lolka2_mut());
///```
#[proc_macro_attribute]
pub fn auto_trait(args: TokenStream, input: TokenStream) -> TokenStream {
let mut input = syn::parse_macro_input!(input as syn::ItemTrait);
let args: syn::Type = match syn::parse(args) {
Ok(args) => args,
Err(error) => {
return syn::Error::new(error.span(), "Argument is required and must be a type").to_compile_error().into()
}
};
let mut args = vec![args];
let mut attrs_to_remove = Vec::new();
for idx in 0..input.attrs.len() {
let attr = &input.attrs[idx];
if attr.path().is_ident("auto_trait") {
match attr.parse_args() {
Ok(arg) => match arg {
syn::Type::Paren(arg) => args.push(*arg.elem),
arg => args.push(arg),
},
Err(error) => {
return syn::Error::new(error.span(), "Argument is required and must be a type").to_compile_error().into()
}
}
attrs_to_remove.push(idx);
}
}
//We need to remove attributes that we're going to parse
for idx in attrs_to_remove {
input.attrs.swap_remove(idx);
}
let mut impls = Vec::new();
for mut args in args.drain(..) {
let trait_name = input.ident.clone();
let mut deref_type = None;
let type_generics = match args {
syn::Type::Path(ref mut typ) => match typ.path.segments.last_mut().expect("To have at least on type path segment").arguments {
syn::PathArguments::AngleBracketed(ref mut args) => {
let mut result = args.clone();
for arg in args.args.iter_mut() {
if let syn::GenericArgument::Constraint(constraint) = arg {
for param in constraint.bounds.iter() {
if let syn::TypeParamBound::Trait(bound) = param {
if bound.path.is_ident(&trait_name) {
if let Some(ident) = deref_type.replace(constraint.ident.clone()) {
return syn::Error::new_spanned(ident, "Multiple bounds to trait, can be problematic so how about no?").to_compile_error().into();
}
}
}
}
let mut segments = syn::punctuated::Punctuated::new();
segments.push(syn::PathSegment {
ident: constraint.ident.clone(),
arguments: syn::PathArguments::None
});
*arg = syn::GenericArgument::Type(syn::Type::Path(syn::TypePath {
qself: None,
path: syn::Path {
leading_colon: None,
segments
},
}));
}
}
if deref_type.is_none() {
if result.args.len() == 1 {
result.args.last_mut();
}
}
Some(result)
},
syn::PathArguments::None => None,
syn::PathArguments::Parenthesized(ref args) => return syn::Error::new_spanned(args, "Unsupported type arguments").to_compile_error().into(),
},
other => {
println!("other={:?}", other);
return syn::Error::new_spanned(other, "Unsupported type").to_compile_error().into();
},
};
let deref_name = deref_type.unwrap_or_else(|| trait_name.clone());
let mut methods = Vec::new();
for item in input.items.iter() {
match item {
syn::TraitItem::Fn(ref method) => {
let method_name = method.sig.ident.clone();
let mut method_args = Vec::new();
for arg in method.sig.inputs.iter() {
match arg {
syn::FnArg::Receiver(arg) => {
if arg.reference.is_some() {
if arg.mutability.is_some() {
method_args.push(quote! {
core::ops::DerefMut::deref_mut(self)
})
} else {
method_args.push(quote! {
core::ops::Deref::deref(self)
})
}
} else {
method_args.push(quote! {
self.into()
})
}
},
syn::FnArg::Typed(arg) => {
let name = &arg.pat;
method_args.push(quote! {
#name
})
},
}
}
let deref_block: syn::Block = syn::parse2(quote! {
{
#deref_name::#method_name(#(#method_args,)*)
}
}).unwrap();
let mut method = method.clone();
method.default = Some(deref_block);
method.semi_token = None;
methods.push(method);
},
unsupported => return syn::Error::new_spanned(unsupported, "Trait contains non-method definitions which is unsupported").to_compile_error().into(),
}
}
impls.push(quote! {
impl#type_generics #trait_name for #args {
#(
#methods
)*
}
});
}
let mut result = quote! {
#input
};
result.extend(impls.drain(..));
result.into()
}