hidden_trait/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3
4// Currently forwarding the type leads to
5// error[E0658]: inherent associated types are unstable
6const FORWARD_ASSICIATED_TYPES: bool = false;
7
8fn impl_expose(input_stream: TokenStream) -> syn::Result<proc_macro2::TokenStream> {
9    let item_impl = syn::parse::<syn::ItemImpl>(input_stream)?;
10    let mut implementations = Vec::new();
11
12    let self_ty = &item_impl.self_ty;
13    let trait_name = match item_impl.trait_ {
14        Some((_, ref path, _)) => path,
15        None => {
16            return Err(syn::Error::new(
17                item_impl.impl_token.span,
18                "Impl must be for a trait",
19            ))
20        }
21    };
22
23    for item in item_impl.items.iter() {
24        implementations.push(match *item {
25            syn::ImplItem::Const(ref impl_const) => {
26                let name = &impl_const.ident;
27                let ty = &impl_const.ty;
28                quote! {
29                    pub const #name: #ty = <#self_ty as #trait_name>::#name;
30                }
31            }
32            syn::ImplItem::Type(ref impl_type) if FORWARD_ASSICIATED_TYPES => {
33                let name = &impl_type.ident;
34                quote! {
35                    pub type #name = <#self_ty as #trait_name>::#name;
36                }
37            }
38            syn::ImplItem::Method(ref impl_method) => {
39                let signature = &impl_method.sig;
40                let name = &signature.ident;
41                let arguments = signature
42                    .inputs
43                    .iter()
44                    .filter_map(|fn_arg| match *fn_arg {
45                        syn::FnArg::Receiver(_) => None,
46                        syn::FnArg::Typed(ref pat_ty) => Some(pat_ty.pat.as_ref()),
47                    })
48                    .collect::<Vec<_>>();
49                quote! {
50                    pub #signature {
51                        #trait_name::#name(self, #(#arguments),*)
52                    }
53                }
54            }
55            _ => continue,
56        });
57    }
58
59    Ok(quote! {
60        #item_impl
61        impl #self_ty {
62            #(#implementations)*
63        }
64    })
65}
66
67#[proc_macro_attribute]
68pub fn expose(_attr: TokenStream, input: TokenStream) -> TokenStream {
69    let stream = match impl_expose(input) {
70        Ok(tokens) => tokens,
71        Err(err) => err.into_compile_error(),
72    };
73    stream.into()
74}