forked from feather-rs/feather
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathentity_metadata.rs
More file actions
335 lines (273 loc) · 8.78 KB
/
entity_metadata.rs
File metadata and controls
335 lines (273 loc) · 8.78 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
use proc_macro::TokenStream;
use proc_macro2::Ident;
use proc_macro2::Span;
use quote::quote;
use std::collections::HashMap;
use syn::braced;
use syn::parenthesized;
use syn::parse::{Parse, ParseBuffer};
use syn::Error;
use syn::Lit;
use syn::Token;
#[derive(Clone)]
struct EntityMetadata {
ident: Ident,
variants: HashMap<Ident, Variant>,
}
impl Parse for EntityMetadata {
fn parse(input: &ParseBuffer) -> Result<Self, Error> {
let ident = input.parse()?;
input.parse::<Token![,]>()?;
let mut variants = HashMap::new();
while let Ok(variant) = input.parse::<Variant>() {
variants.insert(variant.ident.clone(), variant);
input.parse::<Token![,]>()?;
}
Ok(Self { ident, variants })
}
}
#[derive(Clone)]
struct Variant {
ident: Ident,
extends: Option<Ident>,
entries: Vec<Entry>,
}
impl Parse for Variant {
fn parse(input: &ParseBuffer) -> Result<Self, Error> {
let ident = input.parse()?;
let extends = if input.parse::<Token![:]>().is_ok() {
let ident = input.parse()?;
Some(ident)
} else {
None
};
let content;
braced!(content in input);
let mut entries = vec![];
while let Ok(entry) = content.parse::<Entry>() {
entries.push(entry);
}
Ok(Self {
ident,
extends,
entries,
})
}
}
#[derive(Clone)]
struct Entry {
ty: EntryType,
name: Ident,
index: u8,
default: Option<Lit>,
}
impl Parse for Entry {
fn parse(input: &ParseBuffer) -> Result<Self, Error> {
let name = input.parse()?;
let _ = input.parse::<Token![:]>()?;
let ty = input.parse()?;
let paren;
parenthesized!(paren in input);
let default = match paren.parse() {
Ok(val) => Some(val),
Err(_) => None,
};
let _ = input.parse::<Token![=]>()?;
let index = match input.parse::<Lit>()? {
Lit::Int(val) => val.base10_parse()?,
_ => panic!("Index not a `u8`"),
};
let _ = input.parse::<Token![,]>()?;
Ok(Self {
ty,
name,
index,
default,
})
}
}
#[derive(PartialEq, Debug, Display, EnumString, Copy, Clone)]
enum EntryType {
Byte,
VarInt,
Float,
String,
Slot,
Boolean,
OptUuid,
Position,
}
impl Parse for EntryType {
fn parse(input: &ParseBuffer) -> Result<Self, Error> {
let ty = input.parse::<proc_macro2::Ident>()?;
Ok(EntryType::from_rust_type(&ty.to_string()))
}
}
impl EntryType {
fn rust_type(self) -> &'static str {
match self {
EntryType::Byte => "u8",
EntryType::VarInt => "i32",
EntryType::Float => "f32",
EntryType::String => "String",
EntryType::Slot => "Slot",
EntryType::Boolean => "bool",
EntryType::OptUuid => "OptUuid",
EntryType::Position => "BlockPosition",
}
}
fn from_rust_type(ty: &str) -> Self {
match ty {
"u8" => EntryType::Byte,
"VarInt" => EntryType::VarInt,
"f32" => EntryType::Float,
"String" => EntryType::String,
"bool" => EntryType::Boolean,
"Slot" => EntryType::Slot,
"OptUuid" => EntryType::OptUuid,
"BlockPosition" => EntryType::Position,
_ => panic!("Invalid entry type {}", ty),
}
}
}
#[allow(clippy::cognitive_complexity)] // FIXME: clean this function up
pub fn entity_metadata(input: TokenStream) -> TokenStream {
let input: EntityMetadata = syn::parse_macro_input!(input);
let mut structs = vec![];
let mut enum_variants = vec![];
let mut to_raw_metadata_arms = vec![];
let mut to_full_raw_metadata_arms = vec![];
let enum_ident = input.ident.clone();
for variant in input.variants.values() {
let entries = get_metadata_entries(&input, variant.clone());
let variant_ident = &variant.ident;
let mut struct_fields = vec![];
let mut struct_impl = vec![];
let mut to_raw_metadata = vec![];
let mut to_full_raw_metadata = vec![];
let mut new_fn_parameters = vec![];
let mut new_fn_contents = vec![];
let mut default_entries = vec![];
for entry in entries {
let entry_ident = entry.name;
let ty_enum = entry.ty;
let ty = ty_enum.rust_type();
let ty_ident = Ident::new(ty, Span::call_site());
let is_dirty_name = format!("__is_dirty_{}", entry_ident);
let is_dirty_ident = Ident::new(&is_dirty_name, Span::call_site());
struct_fields.push(quote! {
#entry_ident: #ty_ident,
#is_dirty_ident: bool,
});
let set_fn_ident = Ident::new(&format!("set_{}", entry_ident), Span::call_site());
let get_fn_ident = entry_ident.clone();
struct_impl.push(quote! {
pub fn #set_fn_ident(&mut self, val: #ty_ident) {
self.#entry_ident = val;
self.#is_dirty_ident = true;
}
pub fn #get_fn_ident(&self) -> #ty_ident {
self.#entry_ident.clone()
}
});
let pass_reference = ty_enum == EntryType::Slot;
let index = entry.index;
let set_expr = if pass_reference {
quote! { meta.set(#index, self.#entry_ident.clone()); }
} else {
quote! { meta.set(#index, self.#entry_ident); }
};
to_raw_metadata.push(quote! {
if self.#is_dirty_ident {
#set_expr
self.#is_dirty_ident = false;
}
});
to_full_raw_metadata.push(quote! {
#set_expr
});
new_fn_parameters.push(quote! {
#entry_ident: #ty_ident
});
new_fn_contents.push(quote! {
#entry_ident,
#is_dirty_ident: true,
});
to_raw_metadata_arms.push(quote! {
#enum_ident::#variant_ident(meta) => meta.to_raw_metadata(),
});
to_full_raw_metadata_arms.push(quote! {
#enum_ident::#variant_ident(meta) => meta.to_full_raw_metadata(),
});
default_entries.push(match entry.default {
Some(default) => quote! { #entry_ident: #default, #is_dirty_ident: false, },
None => quote! { #entry_ident: Default::default(), #is_dirty_ident: false, },
});
}
struct_impl.push(quote! {
pub fn new(#(#new_fn_parameters),*) -> Self {
Self {
#(#new_fn_contents)*
}
}
fn to_raw_metadata(&mut self) -> EntityMetadata {
let mut meta = EntityMetadata::new();
#(#to_raw_metadata)*
meta
}
fn to_full_raw_metadata(&self) -> EntityMetadata {
let mut meta = EntityMetadata::new();
#(#to_full_raw_metadata)*
meta
}
});
structs.push(quote! {
#[derive(Clone, Debug)]
pub struct #variant_ident {
#(#struct_fields)*
}
impl #variant_ident {
#(#struct_impl)*
}
impl Default for #variant_ident {
fn default() -> Self {
Self {
#(#default_entries)*
}
}
}
});
enum_variants.push(quote! {
#variant_ident(#variant_ident),
})
}
let result = quote! {
#[derive(Clone, Debug)]
pub enum #enum_ident {
#(#enum_variants)*
}
impl #enum_ident {
pub fn to_raw_metadata(&mut self) -> EntityMetadata {
match self {
#(#to_raw_metadata_arms)*
}
}
pub fn to_full_raw_metadata(&self) -> EntityMetadata {
match self {
#(#to_full_raw_metadata_arms)*
}
}
}
#(#structs)*
};
result.into()
}
fn get_metadata_entries(metadata: &EntityMetadata, variant: Variant) -> Vec<Entry> {
let mut entries = vec![];
if let Some(inherits_from) = variant.extends.as_ref() {
let inherits_from = &metadata.variants[inherits_from];
entries.extend(get_metadata_entries(metadata, inherits_from.clone()).into_iter());
}
entries.extend(variant.entries.into_iter());
entries
}