orceh_derive 0.1.1

Derives for orceh
Documentation
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::format_ident;
use quote::quote;
use syn::FnArg;
use syn::ItemTrait;
use syn::TraitItem;
use syn::parse_macro_input;
use syn::parse_quote;

fn validate_input(t: &ItemTrait) {
    t.items.iter().for_each(|item| {
        match item {
            TraitItem::Const(_) => {
                // Maybe these will be supported?
            },
            TraitItem::Fn(_) => {},
            TraitItem::Macro(_) => {
                panic!("Macros are not supported.");
            },
            TraitItem::Type(_) => {
                panic!("Types are not supported");
            },
            TraitItem::Verbatim(_) => {
                panic!("no clue what this is")
            },
            _ => {},
        }
    });
}

fn generate_extern_block(t: &ItemTrait) -> TokenStream2 {
    let functions = t
        .items
        .iter()
        .cloned()
        .filter_map(|item| {
            match item {
                TraitItem::Fn(mut f) => {
                    Some({
                        f.default.take();
                        f
                    })
                },
                _ => None,
            }
        })
        .inspect(|f| {
            if !f.attrs.is_empty() {
                panic!("Attributes are not supported on function types");
            }
        });

    quote! {
        /// We permit these to be unused, because they are only used
        /// to generate the header files for the SDK
        #[allow(unused)]
        unsafe extern "C" {
            #(#functions)*
        }
    }
}

fn generate_plugin_struct(t: &ItemTrait) -> TokenStream2 {
    let vis = &t.vis;
    let name = format_ident!("{}PluginHandle", &t.ident);

    let validate_functions = t.items.iter().filter_map(|item| match item {
        TraitItem::Fn(f) => Some(f),
        _ => None,
    }).map(|f| {

        let func_name = f.sig.ident.to_string();
        let inputs = f.sig.inputs.clone();
        let output = f.sig.output.clone();

        let err_handle = if f.default.is_some() {
            quote! {{}}
        } else {
            quote! {{
                return Err(::orceh::Error::SymbolNotFound(path.to_owned(), #func_name.into()));
            }}
        };

        quote! {
            let maybe_func : Option<::orceh::_exports::libloading::Symbol<unsafe extern fn(#inputs) #output>> = unsafe { handle.get(#func_name.as_bytes()) }.ok();
            if maybe_func.is_none() #err_handle
        }
    });

    let functions = t.items.iter().filter_map(|item| match item {
        TraitItem::Fn(f) => Some(f),
        _ => None,
    }).map(|f| {

        let mut f = f.clone();

        let func_name = f.sig.ident.to_string();
        let inputs = f.sig.inputs.clone();
        let output = f.sig.output.clone();

        let input_idents = inputs.iter().map(|a| match a {
            FnArg::Typed(ty) => ty.pat.clone(),
            _ => panic!("self arguments not supported here")
        });

        let call = if let Some(default) = f.default.take() {
            parse_quote! {{
                let maybe_func: Option<::orceh::_exports::libloading::Symbol<unsafe extern fn(#inputs) #output>> = unsafe { self.handle.get(#func_name.as_bytes()) }.ok();
                if let Some(func) = maybe_func {
                    unsafe { func(#(#input_idents),*) }
                } else #default
            }}
        } else {
            parse_quote! {{
                let func: ::orceh::_exports::libloading::Symbol<unsafe extern fn(#inputs) #output> = unsafe { self.handle.get(#func_name.as_bytes()) }.unwrap();

                unsafe { func(#(#input_idents),*) }
            }}
        };

        f.sig.inputs.insert(0, parse_quote!(&self));
        f.default.replace(call);

        quote! {
            #vis #f
        }
    });

    quote! {
        #vis struct #name {
            handle: ::orceh::_exports::libloading::Library,
        }

        impl #name {
            #vis fn init(path: &std::path::Path) -> Result<Self, ::orceh::Error> {
                let handle = unsafe { ::orceh::_exports::libloading::Library::new(path) }
                    .map_err(|_| ::orceh::Error::LibraryNotFound(path.to_owned()))?;

                #(#validate_functions)*

                Ok(Self {
                    handle
                })
            }

            #(#functions)*
        }
    }
}

#[proc_macro_attribute]
pub fn dylib(_attr: TokenStream, input: TokenStream) -> TokenStream {
    // Parse the input tokens
    let input = parse_macro_input!(input as ItemTrait);

    validate_input(&input);

    let extern_block = generate_extern_block(&input);

    let plugin_struct = generate_plugin_struct(&input);

    let out = quote! {
        #extern_block

        #plugin_struct
    };

    out.into()
}