Skip to main content

tauri_plugin_sync_state_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, DeriveInput, LitStr};
4
5#[proc_macro_derive(SyncState, attributes(sync_state))]
6pub fn derive_sync_state(input: TokenStream) -> TokenStream {
7    let input = parse_macro_input!(input as DeriveInput);
8
9    if matches!(input.data, syn::Data::Union(_)) {
10        return syn::Error::new_spanned(
11            &input.ident,
12            "#[derive(SyncState)] cannot be applied to unions",
13        )
14        .to_compile_error()
15        .into();
16    }
17
18    let ident = &input.ident;
19    let mut name = ident.to_string();
20
21    for attr in &input.attrs {
22        if attr.path().is_ident("sync_state") {
23            let result = attr.parse_nested_meta(|meta| {
24                if meta.path.is_ident("name") {
25                    let lit: LitStr = meta.value()?.parse()?;
26                    name = lit.value();
27                }
28                Ok(())
29            });
30            if let Err(e) = result {
31                return e.to_compile_error().into();
32            }
33        }
34    }
35
36    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
37
38    quote! {
39        impl #impl_generics ::tauri_plugin_sync_state::SyncState for #ident #ty_generics #where_clause {
40            const NAME: &'static str = #name;
41        }
42    }
43    .into()
44}