oasis_runtime_sdk_macros/module_derive/
module.rs

1use proc_macro2::TokenStream;
2use quote::quote;
3
4/// Deriver for the `Module` trait.
5pub struct DeriveModule {
6    /// Items specifying the module configuration.
7    module_cfg: Vec<syn::ImplItem>,
8}
9
10impl DeriveModule {
11    pub fn new() -> Box<Self> {
12        Box::new(Self { module_cfg: vec![] })
13    }
14}
15
16impl super::Deriver for DeriveModule {
17    fn preprocess(&mut self, item: syn::ImplItem) -> Option<syn::ImplItem> {
18        match item {
19            syn::ImplItem::Type(ref ty) => {
20                match ty.ident.to_string().as_str() {
21                    "Error" | "Event" | "Parameters" => {
22                        self.module_cfg.push(item);
23                        None // Take the item.
24                    }
25                    _ => Some(item), // Return the item.
26                }
27            }
28            syn::ImplItem::Const(ref cnst) => {
29                match cnst.ident.to_string().as_str() {
30                    "NAME" | "VERSION" => {
31                        self.module_cfg.push(item);
32                        None // Take the item.
33                    }
34                    _ => Some(item), // Return the item.
35                }
36            }
37            _ => Some(item), // Return the item.
38        }
39    }
40
41    fn derive(&mut self, generics: &syn::Generics, ty: &Box<syn::Type>) -> TokenStream {
42        if self.module_cfg.is_empty() {
43            return quote! {};
44        }
45        let module_cfg = &self.module_cfg;
46
47        quote! {
48            #[automatically_derived]
49            impl #generics sdk::module::Module for #ty {
50                #(#module_cfg)*
51            }
52        }
53    }
54}