Skip to main content

azalea_registry_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{
4    Attribute, Ident, LitStr, Token, braced,
5    parse::{Parse, ParseStream, Result},
6    parse_macro_input,
7    punctuated::Punctuated,
8};
9
10struct Registry {
11    ident: Ident,
12    name: String,
13    items: Vec<RegistryItem>,
14    attrs: Vec<Attribute>,
15}
16
17struct RegistryItem {
18    attrs: Vec<Attribute>,
19    ident: Ident,
20    name: String,
21}
22
23impl Parse for RegistryItem {
24    // Air => "minecraft:air"
25    fn parse(input: ParseStream) -> Result<Self> {
26        // parse annotations like #[default]
27        let attrs = input.call(Attribute::parse_outer).unwrap_or_default();
28
29        let name = input.parse()?;
30        input.parse::<Token![=>]>()?;
31        let id = input.parse::<LitStr>()?.value();
32        Ok(RegistryItem {
33            attrs,
34            ident: name,
35            name: id,
36        })
37    }
38}
39
40impl Parse for Registry {
41    fn parse(input: ParseStream) -> Result<Self> {
42        // enum BlockKind => "block" {
43        //     Air => "minecraft:air",
44        //     Stone => "minecraft:stone"
45        // }
46
47        // this also includes docs
48        let attrs = input.call(Attribute::parse_outer).unwrap_or_default();
49
50        input.parse::<Token![enum]>()?;
51        let ident = input.parse()?;
52
53        input.parse::<Token![=>]>()?;
54        let name = input.parse::<LitStr>()?.value();
55
56        let content;
57        braced!(content in input);
58        let items: Punctuated<RegistryItem, _> =
59            content.parse_terminated(RegistryItem::parse, Token![,])?;
60
61        Ok(Registry {
62            ident,
63            name,
64            items: items.into_iter().collect(),
65            attrs,
66        })
67    }
68}
69
70#[proc_macro]
71pub fn registry(input: TokenStream) -> TokenStream {
72    let input = parse_macro_input!(input as Registry);
73    let name = input.ident;
74    let mut generated = quote! {};
75
76    // enum BlockKind {
77    //     Air = 0,
78    //     Stone,
79    // }
80    let mut enum_items = quote! {};
81    for (i, item) in input.items.iter().enumerate() {
82        let attrs = &item.attrs;
83        let name = &item.ident;
84        let protocol_id = i as u32;
85        enum_items.extend(quote! {
86            #(#attrs)*
87            #name = #protocol_id,
88        });
89    }
90    let attributes = input.attrs;
91    generated.extend(quote! {
92        #(#attributes)*
93        #[derive(azalea_buf::AzBuf, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
94        #[repr(u32)]
95        pub enum #name {
96            #enum_items
97        }
98    });
99
100    let max_id = input.items.len() as u32 - 1;
101
102    let doc_0 = format!("Transmutes a u32 to a {name}.");
103    let doc_1 = format!("The `id` should be at most {max_id}.");
104
105    let registry_name = input.name;
106
107    generated.extend(quote! {
108        impl #name {
109            pub const MAX_ID: u32 = #max_id;
110
111            #[doc = #doc_0]
112            ///
113            /// # Safety
114            #[doc = #doc_1]
115            #[inline]
116            pub unsafe fn from_u32_unchecked(id: u32) -> Self {
117                unsafe { std::mem::transmute::<u32, #name>(id) }
118            }
119            #[inline]
120            pub const fn is_valid_id(id: u32) -> bool {
121                id <= Self::MAX_ID
122            }
123        }
124        impl azalea_registry_builtin::BuiltinRegistry for #name {
125            const NAME: &'static str = #registry_name;
126            fn builtin_from_id(id: u32) -> Option<Self> {
127                if Self::is_valid_id(id) {
128                    Some(unsafe { Self::from_u32_unchecked(id) })
129                } else {
130                    None
131                }
132            }
133            fn builtin_into_id(&self) -> u32 {
134                *self as u32
135            }
136        }
137    });
138
139    let doc_0 = format!("Safely transmutes a u32 to a {name}.");
140
141    generated.extend(quote! {
142        impl TryFrom<u32> for #name {
143            type Error = ();
144
145            #[doc = #doc_0]
146            fn try_from(id: u32) -> Result<Self, Self::Error> {
147                if let Some(value) = azalea_registry_builtin::BuiltinRegistry::builtin_from_id(id) {
148                    Ok(value)
149                } else {
150                    Err(())
151                }
152            }
153        }
154    });
155
156    // Display that uses registry ids
157    let mut to_str_items = quote! {};
158    let mut from_str_items = quote! {};
159    for item in &input.items {
160        let name = &item.ident;
161        let id = &item.name;
162        let namespaced_id = format!("minecraft:{id}");
163
164        to_str_items.extend(quote! {
165            Self::#name => #namespaced_id,
166        });
167        from_str_items.extend(quote! {
168            #id | #namespaced_id => Self::#name,
169        });
170    }
171
172    generated.extend(quote! {
173        impl #name {
174            /// Convert the value to a stringified identifier, formatted like
175            /// `"minecraft:air"`.
176            pub fn to_str(&self) -> &'static str {
177                match self {
178                    #to_str_items
179                }
180            }
181        }
182        const impl azalea_codec::types::ConstFromStr for #name {
183            fn const_from_str(s: &str) -> Option<Self> {
184                Some(match s {
185                    #from_str_items
186                    _ => return None
187                })
188            }
189        }
190        impl std::fmt::Display for #name {
191            /// Convert the value to a stringified identifier, formatted like
192            /// `"minecraft:air"`.
193            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
194                write!(f, "{}", self.to_str())
195            }
196        }
197        impl<'a> TryFrom<&'a ::azalea_core::identifier::Identifier> for #name {
198            type Error = ();
199            fn try_from(ident: &'a ::azalea_core::identifier::Identifier) -> Result<Self, Self::Error> {
200                azalea_codec::types::ConstFromStr::const_from_str(ident.as_ref().1).ok_or(())
201            }
202        }
203        impl TryFrom<::azalea_core::identifier::Identifier> for #name {
204            type Error = ();
205            fn try_from(ident: ::azalea_core::identifier::Identifier) -> Result<Self, Self::Error> {
206                Self::try_from(&ident)
207            }
208        }
209
210        impl<'a> From<#name> for ::azalea_core::identifier::Identifier {
211            fn from(value: #name) -> Self {
212                Self::new(value.to_str())
213            }
214        }
215        /// Parse the value from a stringified identifier, formatted like
216        /// either `"air"` or `"minecraft:air"`.
217        impl std::str::FromStr for #name {
218            type Err = ();
219
220            fn from_str(s: &str) -> Result<Self, Self::Err> {
221                Self::try_from(&::azalea_core::identifier::Identifier::new(s))
222            }
223        }
224
225        impl<O: azalea_codec::Ops> azalea_codec::Codec<O> for #name {
226            fn codec_read(ops: &O) -> azalea_codec::error::ReadResult<Self> {
227                let s = ops.get_string()?;
228                azalea_codec::types::ConstFromStr::const_from_str(&s)
229                    .ok_or_else(|| azalea_codec::error::ReadError::custom(format!("invalid variant '{s}'")))
230            }
231            fn codec_write(&self) -> azalea_codec::error::WriteResult<O> {
232                self.to_string().codec_write()
233            }
234        }
235    });
236
237    generated.into()
238}