Skip to main content

rust_i18n_derive_impl/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{Data, DeriveInput, LitStr, parse_macro_input};
4
5#[proc_macro_derive(Localized, attributes(tag))]
6pub fn localized_derive(input: TokenStream) -> TokenStream {
7    let input = parse_macro_input!(input as DeriveInput);
8    let name = input.ident;
9
10    let variants = match input.data {
11        Data::Enum(d) => d.variants,
12        _ => {
13            return syn::Error::new_spanned(
14                name,
15                "Localized can only be derived for enums",
16            )
17            .to_compile_error()
18            .into();
19        },
20    };
21
22    // We will collect generated match arms here
23    let mut match_arms = Vec::new();
24    // We will collect any errors found here
25    let mut errors = Vec::new();
26
27    for variant in variants {
28        let variant_ident = &variant.ident;
29        let tag_attr = variant
30            .attrs
31            .iter()
32            .find(|attr| attr.path().is_ident("tag"));
33
34        if let Some(attr) = tag_attr {
35            // Try to parse the attribute content
36            match attr.parse_args::<LitStr>() {
37                Ok(literal) => {
38                    let value = literal.value();
39                    match_arms.push(quote! {
40                        Self::#variant_ident => #value
41                    });
42                },
43                Err(e) => {
44                    // Error if format is wrong, e.g. #[tag(123)] instead of string
45                    errors.push(syn::Error::new_spanned(attr, e.to_string()));
46                },
47            }
48        } else {
49            // Error if tag is missing completely
50            // new_spanned(variant) makes the error appear on the variant line itself
51            errors.push(syn::Error::new_spanned(
52                variant.clone(),
53                format!("Missing #[tag(\"...\")] for variant `{}`", variant_ident),
54            ));
55        }
56    }
57
58    // If we found any errors, return them immediately.
59    // This prints nice compiler errors pointing to the specific lines.
60    if !errors.is_empty() {
61        let error_tokens = errors.iter().map(|err| err.to_compile_error());
62        return quote! {
63            #(#error_tokens)*
64        }
65        .into();
66    }
67
68    // If no errors, generate the implementation
69    let expanded = quote! {
70        impl Localized for #name {
71            /// Returns the translation key associated with this variant.
72            fn key(&self) -> &'static str {
73                match self {
74                    #(#match_arms),*
75                }
76            }
77
78            /// Returns the localized string using rust_i18n::t! macro.
79            fn localize(&self) -> std::borrow::Cow<'static, str> {
80                rust_i18n::t!(self.key())
81            }
82        }
83    };
84
85    TokenStream::from(expanded)
86}