dodo_derive/
lib.rs

1//! # Dodo-Derive
2//!
3//! This crate provides Dodo's derive macros.
4use proc_macro::TokenStream;
5
6use quote::quote;
7use syn::{Data, DataStruct, DeriveInput, Fields};
8
9/// Implements the `Entity` trait for your struct. It must contain a field
10/// named `id` of type `Option<Uuid>`.
11#[proc_macro_derive(Entity)]
12pub fn entity_derive(input: TokenStream) -> TokenStream {
13    let ast: DeriveInput = syn::parse(input).unwrap();
14
15    if let Data::Struct(DataStruct { fields: Fields::Named(ref fields), .. }) = &ast.data {
16        if fields.named.iter().any(|field| {
17            match field.ident {
18                Some(ref ident) => ident.to_string() == "id",
19                None => false
20            }
21        }) {
22            impl_entity(&ast)
23        } else {
24            panic!("Entity derive must be used on a struct with a field named \"id\".")
25        }
26    } else {
27        panic!("Entity derive must be used on a struct with named fields.")
28    }
29}
30
31fn impl_entity(ast: &syn::DeriveInput) -> TokenStream {
32    let name = &ast.ident;
33
34    let expanded = quote! {
35        impl dodo::Entity for #name {
36            fn id(&self) -> Option<uuid::Uuid> { self.id }
37            fn set_id(&mut self, id: Option<uuid::Uuid>) { self.id = id }
38        }
39    };
40
41    TokenStream::from(expanded)
42}