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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
use heck::ToSnakeCase;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use syn::{DeriveInput, Ident};
const DEFAULT_DERIVES: &[&str] = &["Debug", "PartialEq", "Eq", "Clone", "Copy"];
use crate::common::{extract_type_ident, filter_fields, get_meta_list, path_to_string};
#[inline]
fn get_helper_macro_name(type_snake: &str) -> Ident {
Ident::new(
&format!("__{}_field_name_variants", type_snake),
Span::call_site(),
)
}
struct FieldNamePair {
variant_ident: Ident,
field_name: String,
}
/// A single field slot in declaration order
enum FieldSlot {
/// One or more consecutive regular fields: (variant_ident, field_name)
Regular(Vec<FieldNamePair>),
/// A nested field - calls to the inner type's helper macro
Nested(Ident),
}
impl FieldSlot {
/// Render each (Variant, "name") as Variant => "name"
fn entries(pairs: &[FieldNamePair]) -> Vec<TokenStream2> {
pairs
.iter()
.map(
|FieldNamePair {
variant_ident,
field_name,
}| quote! { #variant_ident => #field_name },
)
.collect()
}
}
pub struct DeriveFieldName {
vis: syn::Visibility,
ident: Ident,
enum_ident: Ident,
generics: syn::Generics,
enum_derives: Vec<syn::Path>,
extra_attrs: Vec<TokenStream2>,
/// Fields in declaration order, grouped into regular runs and nested slots.
slots: Vec<FieldSlot>,
type_snake: String,
}
impl DeriveFieldName {
pub fn new(input: DeriveInput) -> syn::Result<Self> {
let vis = input.vis;
let ident = input.ident;
let generics = input.generics;
let struct_fields = match input.data {
syn::Data::Struct(s) => s.fields,
_ => {
return Err(syn::Error::new_spanned(
&ident,
"FieldName can only be derived for structs",
));
}
};
let enum_ident = Ident::new(&(ident.to_string() + "FieldName"), Span::call_site());
let derive_attrs_ts =
get_meta_list(&input.attrs, &["stem_name_derive", "ste_name_derive"])?;
//PERF: Could pass code below as closure to avoid collecting into a vector inside get_meta_list
let enum_derives = extract_enum_derives(derive_attrs_ts)?;
let extra_attrs = get_meta_list(&input.attrs, &["stem_name_attr", "ste_name_attr"])?;
let fields = filter_fields(&struct_fields, &["stem_name", "ste_name"])?;
//TODO: allow empty structs by deriving from an empty enum later
if fields.is_empty() {
return Err(syn::Error::new_spanned(
&ident,
"FieldName can only be derived for non-empty structures",
));
}
let type_snake = ident.to_string().to_snake_case();
// Build declaration-order slots: merge consecutive regular fields into one Regular slot.
let mut slots: Vec<FieldSlot> = Vec::new();
for f in &fields {
if f.is_nested {
let inner_type_ident = extract_type_ident(&f.field_ty)?;
let inner_snake = inner_type_ident.to_string().to_snake_case();
slots.push(FieldSlot::Nested(get_helper_macro_name(&inner_snake)));
} else {
let pair = FieldNamePair {
variant_ident: f.variant_ident.to_owned(),
field_name: f.field_ident.to_string(),
};
if let Some(FieldSlot::Regular(pairs)) = slots.last_mut() {
pairs.push(pair);
} else {
slots.push(FieldSlot::Regular(vec![pair]));
}
}
}
Ok(Self {
vis,
ident,
enum_ident,
generics,
enum_derives,
extra_attrs,
slots,
type_snake,
})
}
pub fn expand(&self) -> syn::Result<TokenStream2> {
let has_nested = self.slots.iter().any(|s| matches!(s, FieldSlot::Nested(_)));
if has_nested {
self.expand_nested()
} else {
self.expand_simple()
}
}
fn get_fields_for_simple(&self) -> &Vec<FieldNamePair> {
//PERF: this function is called several times instead of once
debug_assert_eq!(self.slots.len(), 1);
match &self.slots[..] {
[FieldSlot::Regular(p)] => p,
_ => unreachable!("expand_simple called with nested slots"),
}
}
fn expand_simple(&self) -> syn::Result<TokenStream2> {
// No nested fields- exactly one Regular slot.
let pairs = self.get_fields_for_simple();
let entries = FieldSlot::entries(pairs);
let variants: Vec<&Ident> = pairs
.iter()
.map(
|FieldNamePair {
variant_ident,
field_name: _,
}| variant_ident,
)
.collect();
let constructs: Vec<TokenStream2> = variants
.iter()
.map(|v| {
let e = &self.enum_ident;
quote! { #e::#v }
})
.collect();
let vis = &self.vis;
let ident = &self.ident;
let enum_ident = &self.enum_ident;
let derive_attrs = &self.enum_derives;
let extra_attrs = &self.extra_attrs;
let (impl_generics, ty_generics, where_clause) = self.generics.split_for_impl();
let helper_macro_name = get_helper_macro_name(&self.type_snake);
let variant_count = pairs.len();
let own_helper = quote! {
#[doc(hidden)]
#[macro_export]
macro_rules! #helper_macro_name {
($callback:tt; $($acc:tt)*) => {
$callback!{$($acc)* #(#entries,)*}
};
}
};
Ok(quote! {
#[derive(#(#derive_attrs),*)]
#(#[#extra_attrs])*
#vis enum #enum_ident {
#(#variants),*
}
#[automatically_derived]
impl #impl_generics ::struct_to_enum::FieldNames<#variant_count>
for #ident #ty_generics
#where_clause
{
type FieldName = #enum_ident;
fn field_names() -> [Self::FieldName; #variant_count] {
[#(#constructs),*]
}
}
#own_helper
})
}
fn expand_nested(&self) -> syn::Result<TokenStream2> {
let (_impl_generics, ty_generics, _where_clause) = self.generics.split_for_impl();
let type_snake = &self.type_snake;
let builder_macro_name = Ident::new(
&format!("__{}_field_name_build", type_snake),
Span::call_site(),
);
let builder_macro =
self.generate_field_name_builder_macro(&builder_macro_name, &ty_generics);
// Generate one step macro per slot in declaration order.
// Step i receives ($callback:tt; $($acc:tt)*) and then passes the updated
// accumulator to step i+1, or directly to $callback if it's on the last step
let num_slots = self.slots.len();
let step_name = |i: usize| {
Ident::new(
&format!("__{}_field_name_step_{}", type_snake, i),
Span::call_site(),
)
};
let mut step_macros: Vec<TokenStream2> = Vec::new();
for (i, slot) in self.slots.iter().enumerate() {
let this_step = step_name(i);
let is_last = i == num_slots - 1;
match slot {
FieldSlot::Regular(pairs) => {
let entries = FieldSlot::entries(pairs);
if is_last {
step_macros.push(quote! {
#[doc(hidden)]
macro_rules! #this_step {
($callback:tt; $($acc:tt)*) => {
$callback!{$($acc)* #(#entries,)*}
};
}
});
} else {
let next = step_name(i + 1);
step_macros.push(quote! {
#[doc(hidden)]
macro_rules! #this_step {
($callback:tt; $($acc:tt)*) => {
#next!{$callback; $($acc)* #(#entries,)*}
};
}
});
}
}
FieldSlot::Nested(helper_mac) => {
if is_last {
// Last slot: call nested helper with $callback
step_macros.push(quote! {
#[doc(hidden)]
macro_rules! #this_step {
($callback:tt; $($acc:tt)*) => {
#helper_mac!{$callback; $($acc)*}
};
}
});
} else {
// Non-last: nested helper's callback is the next step,
// which receives $callback as its first arg
let next = step_name(i + 1);
step_macros.push(quote! {
#[doc(hidden)]
macro_rules! #this_step {
($callback:tt; $($acc:tt)*) => {
#helper_mac!{#next; $callback; $($acc)*}
};
}
});
}
}
}
}
// Build: step 0 with the builder as callback
let step_0 = step_name(0);
let invocation = quote! { #step_0!{#builder_macro_name;} };
// Finnaly add own helper: when this type is nested in a grandparent,
// just start the same step chain but with the grandparent's callback forwarded as tt.
let helper_macro_name = get_helper_macro_name(type_snake);
let own_helper = quote! {
#[doc(hidden)]
#[macro_export]
macro_rules! #helper_macro_name {
($callback:tt; $($acc:tt)*) => {
#step_0!{$callback; $($acc)*}
};
}
};
Ok(quote! {
#builder_macro
#(#step_macros)*
#own_helper
#invocation
})
}
/// Emit the builder macro that, once it has the full flat list of
/// `Variant => "field_name"` pairs, generates the enum and `From` impl.
fn generate_field_name_builder_macro(
&self,
macro_name: &Ident,
ty_generics: &syn::TypeGenerics,
) -> TokenStream2 {
let vis = &self.vis;
let enum_ty = &self.enum_ident;
let derive = &self.enum_derives;
let attrs = &self.extra_attrs;
let ty = &self.ident;
let (impl_generics, _, where_clause) = self.generics.split_for_impl();
quote! {
#[doc(hidden)]
macro_rules! #macro_name {
($($variant:ident => $name_str:expr,)*) => {
#[derive(#(#derive),*)]
#(#[#attrs])*
#vis enum #enum_ty {
$($variant),*
}
#[automatically_derived]
impl #impl_generics ::struct_to_enum::FieldNames<{ let mut _n = 0usize; $({ let _ = stringify!($variant); _n += 1; })* _n }>
for #ty #ty_generics
#where_clause
{
type FieldName = #enum_ty;
fn field_names() -> [Self::FieldName; { let mut _n = 0usize; $({ let _ = stringify!($variant); _n += 1; })* _n }] {
[$(#enum_ty::$variant),*]
}
}
};
}
}
}
// TODO: for later (maybe could reuse implementation)
#[allow(dead_code)]
fn generate_field_names_impl(
&self,
ty_generics: &syn::TypeGenerics,
variants: TokenStream2,
) -> TokenStream2 {
let variant_count = self.slots.len();
let ty = &self.ident;
let (impl_generics, _, where_clause) = self.generics.split_for_impl();
let enum_ty = &self.enum_ident;
quote! {
impl #impl_generics ::struct_to_enum::FieldNames<#variant_count>
for #ty #ty_generics
#where_clause
{
type FieldName = #enum_ty;
fn field_names() -> [Self::FieldName; #variant_count] {
[$(#enum_ty::$variant),*]
#variants
}
}
}
}
}
fn extract_enum_derives(derive_attrs_ts: Vec<TokenStream2>) -> syn::Result<Vec<syn::Path>> {
let mut merge_defaults = true;
let mut enum_derives: Vec<syn::Path> = Vec::new();
for ts in derive_attrs_ts {
// For each row, collect derive attributes into `enum_derives` and look for `no_defaults` flag
let mut iter = ts.into_iter().peekable();
while let Some(tt) = iter.next() {
match tt {
proc_macro2::TokenTree::Ident(id) => {
if id == "no_defaults" {
if matches!(
iter.peek(),
Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == '='
) {
iter.next(); // consume `=`
merge_defaults = match iter.next() {
Some(proc_macro2::TokenTree::Ident(val)) if val == "true" => true,
Some(proc_macro2::TokenTree::Ident(val)) if val == "false" => false,
Some(unexpected) => {
return Err(syn::Error::new_spanned(
&unexpected,
"expected `true` or `false` for `no_defaults` flag",
));
}
None => {
return Err(syn::Error::new(
proc_macro2::Span::call_site(),
"unexpected end of input: expected `true` or `false` after `no_defaults =`",
));
}
};
} else {
merge_defaults = true; // bare flag
}
} else {
// Consume `::Ident` segments to build a full path
let mut segments =
syn::punctuated::Punctuated::<syn::PathSegment, syn::Token![::]>::new();
segments.push(syn::PathSegment::from(id));
while matches!(
iter.peek(),
Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ':'
) {
iter.next(); // consume first `:`
iter.next(); // consume second `:`
match iter.next() {
Some(proc_macro2::TokenTree::Ident(next_id)) => {
segments.push(syn::PathSegment::from(next_id));
}
Some(unexpected) => {
return Err(syn::Error::new_spanned(
&unexpected,
"expected identifier after `::`",
));
}
None => {
return Err(syn::Error::new(
proc_macro2::Span::call_site(),
"unexpected end of input: expected identifier after `::`",
));
}
}
}
enum_derives.push(syn::Path {
leading_colon: None,
segments,
});
}
}
proc_macro2::TokenTree::Punct(_) => {}
unexpected => {
return Err(syn::Error::new_spanned(
&unexpected,
"unexpected token in derive attribute",
));
}
}
}
}
if merge_defaults {
for &d_derive in DEFAULT_DERIVES {
if !enum_derives.iter().any(|p| path_to_string(p) == d_derive) {
let d_path: syn::Path =
syn::parse_str(d_derive).expect("invalid default derive path");
enum_derives.push(d_path);
}
}
}
Ok(enum_derives)
}