Advertisement
Guest User

Untitled

a guest
Sep 7th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.86 KB | None | 0 0
  1. extern crate proc_macro;
  2. extern crate syn;
  3. #[macro_use]
  4. extern crate quote;
  5.  
  6. use proc_macro::TokenStream;
  7.  
  8. fn impl_hello_world(ast: &syn::DeriveInput) -> quote::Tokens {
  9.     let name = &ast.ident;
  10.     // Check if derive(HelloWorld) was specified for a struct
  11.     if let syn::Body::Struct(ref _struct) = ast.body {
  12.         match _struct {
  13.            
  14.             syn::VariantData::Struct(fields) => {
  15.                 // println!("its a struct, {:#?}", fields)
  16.                 for field in fields {
  17.                     match field.ty {
  18.                         syn::Ty::Path(ref opt, ref path) => {
  19.                             println!("----{:?}", path)
  20.                         },
  21.                         _ => println!("unknown")
  22.                     }
  23.                     println!("{:#?}", field.ty);
  24.                     // println!("x: {:?}", field.ident.clone().unwrap());
  25.                 }
  26.  
  27.             },
  28.             _ => panic!("Interpolate is only defined for structs"),
  29.         };
  30.         // Yes, this is a struct
  31.  
  32.         // println!("ast:{:#?}", s);
  33.  
  34.  
  35.         quote! {
  36.             impl HelloWorld for #name {
  37.                 fn hello_world() {
  38.                     println!("Hello, World! My name is {}", stringify!(#name));
  39.                 }
  40.             }
  41.         }
  42.     } else {
  43.         // Nope. This is an Enum. We cannot handle these!
  44.         panic!("#[derive(HelloWorld)] is only defined for structs, not for enums!");
  45.     }
  46. }
  47.  
  48. #[proc_macro_derive(HelloWorld)]
  49. pub fn hello_world(input: TokenStream) -> TokenStream {
  50.     // Construct a string representation of the type definition
  51.     let s = input.to_string();
  52.    
  53.     // Parse the string representation
  54.     let ast = syn::parse_derive_input(&s).unwrap();
  55.  
  56.     // Build the impl
  57.     let gen = impl_hello_world(&ast);
  58.    
  59.     // Return the generated impl
  60.     gen.parse().unwrap()
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement