Last active
July 21, 2023 11:18
-
-
Save nmrshll/756831858f83895deb04fe7f282d5835 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use derive_simple::DeriveSimple; | |
use proc_macro::TokenStream as TokenStream1; | |
use quote::quote; | |
use syn::DeriveInput; | |
#[proc_macro_derive(Simple)] | |
pub fn derive_simple(input: TokenStream1) -> TokenStream1 { | |
let derive_simple = DeriveSimple { | |
input: syn::parse_macro_input!(input as DeriveInput), | |
}; | |
let code_derive_simple = derive_simple.to_code(); | |
TokenStream1::from(quote! { | |
#code_derive_simple | |
}) | |
} | |
mod derive_simple { | |
use proc_macro2::TokenStream as TokenStream2; | |
use quote::quote; | |
use syn::DeriveInput; | |
pub struct DeriveSimple { | |
pub input: DeriveInput, | |
} | |
impl DeriveSimple { | |
pub fn from_input(input: &DeriveInput) -> DeriveSimple { | |
DeriveSimple { | |
input: input.clone(), | |
} | |
} | |
pub fn to_code(&self) -> TokenStream2 { | |
let name = &self.input.ident; | |
let gen = quote! { | |
impl #name { | |
fn say_my_name() -> String { | |
format!("Hello, Macro! My name is {}", stringify!(#name)) | |
} | |
} | |
}; | |
gen.into() | |
} | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use proc_macro2::TokenStream as TokenStream2; | |
use quote::quote; | |
use syn::DeriveInput; | |
use crate::derive_simple::DeriveSimple; | |
fn derive_input(input: TokenStream2) -> DeriveInput { | |
syn::parse2::<DeriveInput>(input).unwrap() | |
} | |
#[test] | |
fn test_my_macro() { | |
let input_enum: DeriveInput = derive_input(quote! { | |
enum TestErrors { | |
#[error("some_error")] | |
NotFound, | |
#[error("some_error")] | |
ServerError, | |
} | |
}); | |
let output = DeriveSimple::from_input(&input_enum).to_code(); | |
dbg!(&output); | |
assert_eq!(output.to_string(), ""); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment