unitval_derive/
ast.rs

1use crate::unit;
2use proc_macro2::TokenStream;
3use quote::quote;
4use syn::DeriveInput;
5
6pub fn impl_as_unit_val(input: &DeriveInput, tokens: &unit::Tokens) -> TokenStream {
7    let ident = &input.ident;
8    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
9    let as_tokens = &tokens.as_tokens;
10    quote! {
11        impl #impl_generics ::unitval::AsUnitVal for #ident #ty_generics #where_clause {
12            fn as_unitval(&self) -> &'static str {
13                match self {
14                    #as_tokens
15                }
16            }
17        }
18    }
19}
20
21pub fn impl_from_unit_val(input: &DeriveInput, tokens: &unit::Tokens) -> TokenStream {
22    let ident = &input.ident;
23    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
24    let from_tokens = &tokens.from_tokens;
25    quote! {
26        impl #impl_generics ::unitval::FromUnitVal for #ident #ty_generics #where_clause {
27            fn from_unitval(value: &str) -> ::std::io::Result<Self> {
28                match value {
29                    #from_tokens
30                    _ => Err(::std::io::Error::new(
31                        ::std::io::ErrorKind::InvalidInput,
32                        format!("unknown unitval {:?} for {}", value, stringify!(#ident)),
33                    ))
34                }
35            }
36        }
37    }
38}