Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate proc_macro;
- extern crate syn;
- #[macro_use]
- extern crate quote;
- use proc_macro::TokenStream;
- fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens {
- let name = &ast.ident;
- // Check if derive(HelloWorld) was specified for a struct
- if let syn::Body::Struct(ref _struct) = ast.body {
- match _struct {
- syn::VariantData::Struct(fields) => {
- // println!("its a struct, {:#?}", fields)
- for field in fields {
- match field.ty {
- syn::Ty::Path(ref opt, ref path) => {
- println!("----{:?}", path)
- },
- _ => println!("unknown")
- }
- println!("{:#?}", field.ty);
- // println!("x: {:?}", field.ident.clone().unwrap());
- }
- },
- _ => panic!("Interpolate is only defined for structs"),
- };
- // Yes, this is a struct
- // println!("ast:{:#?}", s);
- quote! {
- impl HelloWorld for #name {
- fn hello_world() {
- println!("Hello, World! My name is {}", stringify!(#name));
- }
- }
- }
- } else {
- // Nope. This is an Enum. We cannot handle these!
- panic!("#[derive(HelloWorld)] is only defined for structs, not for enums!");
- }
- }
- #[proc_macro_derive(HelloWorld)]
- pub fn hello_world(input: TokenStream) -> TokenStream {
- // Construct a string representation of the type definition
- let s = input.to_string();
- // Parse the string representation
- let ast = syn::parse_derive_input(&s).unwrap();
- // Build the impl
- let gen = impl_hello_world(&ast);
- // Return the generated impl
- gen.parse().unwrap()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement