aboutsummaryrefslogtreecommitdiff
path: root/azalea-registry/azalea-registry-macros/src/lib.rs
blob: 5cb359829d81a8df9c856cb744310dd390fad8c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    Attribute, Ident, LitStr, Token, braced,
    parse::{Parse, ParseStream, Result},
    parse_macro_input,
    punctuated::Punctuated,
};

struct Registry {
    name: Ident,
    items: Vec<RegistryItem>,
    attrs: Vec<Attribute>,
}

struct RegistryItem {
    attrs: Vec<Attribute>,
    name: Ident,
    id: String,
}

impl Parse for RegistryItem {
    // Air => "minecraft:air"
    fn parse(input: ParseStream) -> Result<Self> {
        // parse annotations like #[default]
        let attrs = input.call(Attribute::parse_outer).unwrap_or_default();

        let name = input.parse()?;
        input.parse::<Token![=>]>()?;
        let id = input.parse::<LitStr>()?.value();
        Ok(RegistryItem { attrs, name, id })
    }
}

impl Parse for Registry {
    fn parse(input: ParseStream) -> Result<Self> {
        // enum BlockKind {
        //     Air => "minecraft:air",
        //     Stone => "minecraft:stone"
        // }

        // this also includes docs
        let attrs = input.call(Attribute::parse_outer).unwrap_or_default();

        input.parse::<Token![enum]>()?;
        let name = input.parse()?;
        let content;
        braced!(content in input);
        let items: Punctuated<RegistryItem, _> =
            content.parse_terminated(RegistryItem::parse, Token![,])?;

        Ok(Registry {
            name,
            items: items.into_iter().collect(),
            attrs,
        })
    }
}

#[proc_macro]
pub fn registry(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as Registry);
    let name = input.name;
    let mut generated = quote! {};

    // enum BlockKind {
    //     Air = 0,
    //     Stone,
    // }
    let mut enum_items = quote! {};
    for (i, item) in input.items.iter().enumerate() {
        let attrs = &item.attrs;
        let name = &item.name;
        let protocol_id = i as u32;
        enum_items.extend(quote! {
            #(#attrs)*
            #name = #protocol_id,
        });
    }
    let attributes = input.attrs;
    generated.extend(quote! {
        #(#attributes)*
        #[derive(azalea_buf::AzBuf, Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
        #[repr(u32)]
        pub enum #name {
            #enum_items
        }
    });

    let max_id = input.items.len() as u32 - 1;

    let doc_0 = format!("Transmutes a u32 to a {name}.");
    let doc_1 = format!("The `id` should be at most {max_id}.");

    generated.extend(quote! {
        impl #name {
            #[doc = #doc_0]
            ///
            /// # Safety
            #[doc = #doc_1]
            #[inline]
            pub unsafe fn from_u32_unchecked(id: u32) -> Self {
                std::mem::transmute::<u32, #name>(id)
            }

            #[inline]
            pub const fn is_valid_id(id: u32) -> bool {
                id <= #max_id
            }
        }
        impl crate::Registry for #name {
            fn from_u32(value: u32) -> Option<Self> {
                if Self::is_valid_id(value) {
                    Some(unsafe { Self::from_u32_unchecked(value) })
                } else {
                    None
                }
            }
            fn to_u32(&self) -> u32 {
                *self as u32
            }
        }
    });

    let doc_0 = format!("Safely transmutes a u32 to a {name}.");

    generated.extend(quote! {
        impl TryFrom<u32> for #name {
            type Error = ();

            #[doc = #doc_0]
            fn try_from(id: u32) -> Result<Self, Self::Error> {
                if let Some(value) = crate::Registry::from_u32(id) {
                    Ok(value)
                } else {
                    Err(())
                }
            }
        }
    });

    // Display that uses registry ids
    let mut to_str_items = quote! {};
    let mut from_str_items = quote! {};
    for item in &input.items {
        let name = &item.name;
        let id = &item.id;
        to_str_items.extend(quote! {
            Self::#name => concat!("minecraft:", #id),
        });
        from_str_items.extend(quote! {
            #id => Ok(Self::#name),
        });
    }
    generated.extend(quote! {
        impl #name {
            /// Convert the value to a stringified identifier, formatted like
            /// `"minecraft:air"`.
            pub fn to_str(&self) -> &'static str {
                match self {
                    #to_str_items
                }
            }
        }
        impl std::fmt::Display for #name {
            /// Convert the value to a stringified identifier, formatted like
            /// `"minecraft:air"`.
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.to_str())
            }
        }
        impl<'a> TryFrom<&'a crate::Identifier> for #name {
            type Error = ();
            fn try_from(ident: &'a crate::Identifier) -> Result<Self, Self::Error> {
                if ident.namespace() != "minecraft" { return Err(()) }
                match ident.path() {
                    #from_str_items
                    _ => return Err(()),
                }
            }
        }
        impl<'a> From<#name> for crate::Identifier {
            fn from(value: #name) -> Self {
                Self::new(value.to_str())
            }
        }
        /// Parse the value from a stringified identifier, formatted like
        /// either `"air"` or `"minecraft:air"`.
        impl std::str::FromStr for #name {
            type Err = ();

            fn from_str(s: &str) -> Result<Self, Self::Err> {
                Self::try_from(&crate::Identifier::new(s))
            }
        }

        #[cfg(feature = "serde")]
        impl serde::Serialize for #name {
            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
            where
                S: serde::Serializer,
            {
                serializer.serialize_str(&self.to_string())
            }
        }
        #[cfg(feature = "serde")]
        impl<'de> serde::Deserialize<'de> for #name {
            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                let s = String::deserialize(deserializer)?;
                s.parse().map_err(|_| serde::de::Error::custom(
                    format!("{s:?} is not a valid {name}", s = s, name = stringify!(#name))
                ))
            }
        }

        impl simdnbt::FromNbtTag for #name {
            fn from_nbt_tag(tag: simdnbt::borrow::NbtTag) -> Option<Self> {
                let v = tag.string()?;
                std::str::FromStr::from_str(&v.to_str()).ok()
            }
        }
        impl simdnbt::ToNbtTag for #name {
            fn to_nbt_tag(self) -> simdnbt::owned::NbtTag {
                simdnbt::owned::NbtTag::String(self.to_string().into())
            }
        }
    });

    generated.into()
}