oneof_derive 0.2.0

Proc macro implementation for the OneOf derive macro
Documentation
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote;
use std::collections::BTreeMap;
use syn::{parse_macro_input, Data, DeriveInput, Fields, Type};

/// Convert a variant ident (CamelCase) to snake_case, returning:
/// - `method_ident`: the Ident to use as the method name (raw if keyword)
/// - `base_name`: the plain string without `r#` prefix, used to construct
///   `{name}_mut`, `into_{name}`, `is_{name}` without raw-ident ambiguity.
fn to_snake_case(ident: &Ident) -> (Ident, String) {
    let s = ident.to_string();
    let chars: Vec<char> = s.chars().collect();
    let mut result = String::with_capacity(s.len() + 4);

    for i in 0..chars.len() {
        let c = chars[i];
        if c.is_uppercase() {
            if i > 0 {
                let prev = chars[i - 1];
                // Insert `_` between:
                //   lower → upper  (e.g. "notFound" → "not_found")
                //   upper → lower  (e.g. "HTTPError" → "http_error")
                // but NOT within a consecutive-uppercase group.
                if prev.is_lowercase() || (i + 1 < chars.len() && chars[i + 1].is_lowercase()) {
                    result.push('_');
                }
            }
            result.extend(c.to_lowercase());
        } else {
            result.push(c);
        }
    }

    let span = ident.span();
    if is_rust_keyword(&result) {
        (Ident::new_raw(&result, span), result)
    } else {
        (Ident::new(&result, span), result)
    }
}

fn is_rust_keyword(s: &str) -> bool {
    matches!(
        s,
        "abstract"
            | "as"
            | "async"
            | "await"
            | "become"
            | "box"
            | "break"
            | "const"
            | "continue"
            | "crate"
            | "do"
            | "dyn"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "final"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "macro"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "override"
            | "priv"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "Self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "try"
            | "type"
            | "typeof"
            | "union"
            | "unsafe"
            | "unsized"
            | "use"
            | "virtual"
            | "where"
            | "while"
            | "yield"
    )
}

/// Create `{base}_mut`, `into_{base}`, `is_{base}` idents from the base name string.
fn method_idents(base_name: &str, span: proc_macro2::Span) -> (Ident, Ident, Ident) {
    let mut_name = Ident::new(&format!("{base_name}_mut"), span);
    let into_name = Ident::new(&format!("into_{base_name}"), span);
    let is_name = Ident::new(&format!("is_{base_name}"), span);
    (mut_name, into_name, is_name)
}

fn generate_unit_methods(
    variant_ident: &Ident,
    method_ident: &Ident,
    base_name: &str,
) -> proc_macro2::TokenStream {
    let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
    let v = variant_ident.to_string();
    let doc_ref = format!("Returns `Some(())` if this value is `{v}`, otherwise `None`.");
    let doc_mut = format!("Returns `Some(())` if this value is `{v}`, otherwise `None`.");
    let doc_into =
        format!("Consumes `self` and returns `Some(())` if this value is `{v}`, otherwise `None`.");
    let doc_is = format!("Returns `true` if this value is `{v}`.");
    quote! {
        #[doc = #doc_ref]
        pub fn #method_ident(&self) -> Option<()> {
            match self {
                Self::#variant_ident => Some(()),
                _ => None,
            }
        }

        #[doc = #doc_mut]
        pub fn #method_mut(&mut self) -> Option<()> {
            match self {
                Self::#variant_ident => Some(()),
                _ => None,
            }
        }

        #[doc = #doc_into]
        pub fn #into_method(self) -> Option<()> {
            match self {
                Self::#variant_ident => Some(()),
                _ => None,
            }
        }

        #[doc = #doc_is]
        pub fn #is_method(&self) -> bool {
            matches!(self, Self::#variant_ident)
        }
    }
}

fn generate_unnamed_methods(
    fields: &syn::FieldsUnnamed,
    variant_ident: &Ident,
    method_ident: &Ident,
    base_name: &str,
) -> proc_macro2::TokenStream {
    let field_count = fields.unnamed.len();
    let pat_vars: Vec<Ident> = (0..field_count)
        .map(|i| {
            let name = if field_count == 1 {
                "v".to_string()
            } else {
                format!("v{i}")
            };
            Ident::new(&name, variant_ident.span())
        })
        .collect();
    let field_tys: Vec<&Type> = fields.unnamed.iter().map(|f| &f.ty).collect();
    let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
    let v = variant_ident.to_string();
    let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_into = format!(
        "Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
    );
    let doc_is = format!("Returns `true` if this value is `{v}`.");

    let ref_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &#ty }).collect();
    let mut_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &mut #ty }).collect();

    quote! {
        #[doc = #doc_ref]
        pub fn #method_ident(&self) -> Option<(#(#ref_tys),*)> {
            match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
        }

        #[doc = #doc_mut]
        pub fn #method_mut(&mut self) -> Option<(#(#mut_tys),*)> {
            match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
        }

        #[doc = #doc_into]
        pub fn #into_method(self) -> Option<(#(#field_tys),*)> {
            match self { Self::#variant_ident(#(#pat_vars),*) => Some((#(#pat_vars),*)), _ => None }
        }

        #[doc = #doc_is]
        pub fn #is_method(&self) -> bool {
            matches!(self, Self::#variant_ident(..))
        }
    }
}

/// 单字段命名变体:保持当前行为,直接返回 `Option<&T>`
fn generate_named_single_methods(
    fields: &syn::FieldsNamed,
    variant_ident: &Ident,
    method_ident: &Ident,
    base_name: &str,
) -> proc_macro2::TokenStream {
    let field_idents: Vec<&Ident> = fields
        .named
        .iter()
        .map(|f| f.ident.as_ref().unwrap())
        .collect();
    let field_tys: Vec<&Type> = fields.named.iter().map(|f| &f.ty).collect();
    let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
    let v = variant_ident.to_string();
    let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_into = format!(
        "Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
    );
    let doc_is = format!("Returns `true` if this value is `{v}`.");

    let ref_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &#ty }).collect();
    let mut_tys: Vec<_> = field_tys.iter().map(|ty| quote! { &mut #ty }).collect();

    quote! {
        #[doc = #doc_ref]
        pub fn #method_ident(&self) -> Option<(#(#ref_tys),*)> {
            match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
        }

        #[doc = #doc_mut]
        pub fn #method_mut(&mut self) -> Option<(#(#mut_tys),*)> {
            match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
        }

        #[doc = #doc_into]
        pub fn #into_method(self) -> Option<(#(#field_tys),*)> {
            match self { Self::#variant_ident { #(#field_idents),* } => Some((#(#field_idents),*)), _ => None }
        }

        #[doc = #doc_is]
        pub fn #is_method(&self) -> bool {
            matches!(self, Self::#variant_ident { .. })
        }
    }
}

/// 多字段命名变体:生成 `FooRef<'a>`、`FooRefMut<'a>`、`FooOwned` 结构体,
/// 方法返回这些结构体以保留字段名。
fn generate_named_multi_methods(
    fields: &syn::FieldsNamed,
    variant_ident: &Ident,
    method_ident: &Ident,
    base_name: &str,
    enum_generics: &syn::Generics,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let field_idents: Vec<&Ident> = fields
        .named
        .iter()
        .map(|f| f.ident.as_ref().unwrap())
        .collect();
    let field_tys: Vec<&Type> = fields.named.iter().map(|f| &f.ty).collect();
    let (method_mut, into_method, is_method) = method_idents(base_name, method_ident.span());
    let v = variant_ident.to_string();
    let doc_ref = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_mut = format!("Returns `Some(...)` if this value is `{v}`, otherwise `None`.");
    let doc_into = format!(
        "Consumes `self` and returns `Some(...)` if this value is `{v}`, otherwise `None`."
    );
    let doc_is = format!("Returns `true` if this value is `{v}`.");

    // 结构体命名:用变体原名(PascalCase)+ 后缀
    let ref_struct_name = Ident::new(&format!("{v}Ref"), variant_ident.span());
    let ref_mut_struct_name = Ident::new(&format!("{v}RefMut"), variant_ident.span());
    let owned_struct_name = Ident::new(&format!("{v}Owned"), variant_ident.span());

    // 提取枚举的泛型参数(不含 where 约束),用于结构体定义
    let gen_params = &enum_generics.params;
    let (_impl_gen, ty_gen, _where) = enum_generics.split_for_impl();

    // 结构体定义
    let struct_defs = quote! {
        /// 不可变引用投影,保留原始字段名
        #[allow(non_camel_case_types)]
        #[derive(Debug, PartialEq)]
        pub struct #ref_struct_name <'a, #gen_params> {
            #(pub #field_idents: &'a #field_tys),*
        }

        /// 可变引用投影,保留原始字段名
        #[allow(non_camel_case_types)]
        #[derive(Debug, PartialEq)]
        pub struct #ref_mut_struct_name <'a, #gen_params> {
            #(pub #field_idents: &'a mut #field_tys),*
        }

        /// 所有权投影,保留原始字段名
        #[allow(non_camel_case_types)]
        #[derive(Debug, PartialEq)]
        pub struct #owned_struct_name #ty_gen {
            #(pub #field_idents: #field_tys),*
        }
    };

    // 方法定义
    let methods = quote! {
        #[doc = #doc_ref]
        pub fn #method_ident(&self) -> Option<#ref_struct_name<'_, #gen_params>> {
            match self {
                Self::#variant_ident { #(#field_idents),* } => {
                    Some(#ref_struct_name { #(#field_idents),* })
                }
                _ => None,
            }
        }

        #[doc = #doc_mut]
        pub fn #method_mut(&mut self) -> Option<#ref_mut_struct_name<'_, #gen_params>> {
            match self {
                Self::#variant_ident { #(#field_idents),* } => {
                    Some(#ref_mut_struct_name { #(#field_idents),* })
                }
                _ => None,
            }
        }

        #[doc = #doc_into]
        pub fn #into_method(self) -> Option<#owned_struct_name #ty_gen> {
            match self {
                Self::#variant_ident { #(#field_idents),* } => {
                    Some(#owned_struct_name { #(#field_idents),* })
                }
                _ => None,
            }
        }

        #[doc = #doc_is]
        pub fn #is_method(&self) -> bool {
            matches!(self, Self::#variant_ident { .. })
        }
    };

    (struct_defs, methods)
}

/// Check that no two variants generate the same method name.
/// If conflicts exist, return compile errors pointing at the conflicting variants.
fn check_method_conflicts(variants: &[(&syn::Ident, &str)]) -> Result<(), Vec<syn::Error>> {
    let mut name_map: BTreeMap<String, Vec<&syn::Ident>> = BTreeMap::new();

    for (variant_ident, base_name) in variants {
        name_map
            .entry(base_name.to_string())
            .or_default()
            .push(variant_ident);
        name_map
            .entry(format!("{base_name}_mut"))
            .or_default()
            .push(variant_ident);
        name_map
            .entry(format!("into_{base_name}"))
            .or_default()
            .push(variant_ident);
        name_map
            .entry(format!("is_{base_name}"))
            .or_default()
            .push(variant_ident);
    }

    let errors: Vec<syn::Error> = name_map
        .iter()
        .filter(|(_, idents)| idents.len() > 1)
        .map(|(name, idents)| {
            let v0 = idents[0];
            let v1 = idents[1];
            let msg = format!(
                "OneOf generates duplicated method `{name}` from variants `{v0}` and `{v1}`.\n\
                 Rename one of the variants to resolve the conflict."
            );
            syn::Error::new(v0.span(), msg)
        })
        .collect();

    if errors.is_empty() {
        Ok(())
    } else {
        Err(errors)
    }
}

#[proc_macro_derive(OneOf)]
pub fn derive_one_of(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    match &input.data {
        Data::Enum(enum_data) => {
            let enum_name = &input.ident;
            let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

            // First pass: collect base names and check for conflicts
            let variant_bases: Vec<(&syn::Ident, String)> = enum_data
                .variants
                .iter()
                .map(|v| {
                    let (_, base_name) = to_snake_case(&v.ident);
                    (&v.ident, base_name)
                })
                .collect();

            let variant_refs: Vec<(&syn::Ident, &str)> = variant_bases
                .iter()
                .map(|(id, s)| (*id, s.as_str()))
                .collect();

            if let Err(errors) = check_method_conflicts(&variant_refs) {
                return errors
                    .into_iter()
                    .map(|e| e.to_compile_error())
                    .fold(proc_macro2::TokenStream::new(), |mut acc, ts| {
                        acc.extend(ts);
                        acc
                    })
                    .into();
            }

            // Second pass: generate code for each variant
            let mut struct_defs = proc_macro2::TokenStream::new();
            let variant_methods: Vec<_> = enum_data
                .variants
                .iter()
                .map(|variant| {
                    let variant_ident = &variant.ident;
                    let (method_ident, base_name) = to_snake_case(variant_ident);

                    match &variant.fields {
                        Fields::Unit => {
                            generate_unit_methods(variant_ident, &method_ident, &base_name)
                        }
                        Fields::Unnamed(fields) => generate_unnamed_methods(
                            fields,
                            variant_ident,
                            &method_ident,
                            &base_name,
                        ),
                        Fields::Named(fields) if fields.named.len() > 1 => {
                            let (structs, methods) = generate_named_multi_methods(
                                fields,
                                variant_ident,
                                &method_ident,
                                &base_name,
                                &input.generics,
                            );
                            struct_defs.extend(structs);
                            methods
                        }
                        Fields::Named(fields) => generate_named_single_methods(
                            fields,
                            variant_ident,
                            &method_ident,
                            &base_name,
                        ),
                    }
                })
                .collect();

            let expanded = quote! {
                #struct_defs
                impl #impl_generics #enum_name #ty_generics #where_clause {
                    #(#variant_methods)*
                }
            };
            expanded.into()
        }
        Data::Struct(_) | Data::Union(_) => {
            syn::Error::new(input.ident.span(), "OneOf can only be derived on enums")
                .to_compile_error()
                .into()
        }
    }
}