const-type-layout-derive 0.3.1

Derive macro implementation for const-type-layout crate
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io]
//! [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
//! [![License Status]][fossa] [![Code Coverage]][codecov]
//! [![Gitpod Ready-to-Code]][gitpod]
//!
//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/const-type-layout/ci.yml?branch=main
//! [workflow]: https://github.com/juntyr/const-type-layout/actions/workflows/ci.yml?query=branch%3Amain
//!
//! [MSRV]: https://img.shields.io/badge/MSRV-1.78.0--nightly-orange
//! [repo]: https://github.com/juntyr/const-type-layout
//!
//! [Latest Version]: https://img.shields.io/crates/v/const-type-layout
//! [crates.io]: https://crates.io/crates/const-type-layout
//!
//! [Rust Doc Crate]: https://img.shields.io/docsrs/const-type-layout
//! [docs.rs]: https://docs.rs/const-type-layout/
//!
//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
//! [docs]: https://juntyr.github.io/const-type-layout/const_type_layout
//!
//! [License Status]: https://app.fossa.com/api/projects/custom%2B26490%2Fgithub.com%2Fjuntyr%2Fconst-type-layout.svg?type=shield
//! [fossa]: https://app.fossa.com/projects/custom%2B26490%2Fgithub.com%2Fjuntyr%2Fconst-type-layout?ref=badge_shield
//!
//! [Code Coverage]: https://img.shields.io/codecov/c/github/juntyr/const-type-layout?token=J39WVBIMZX
//! [codecov]: https://codecov.io/gh/juntyr/const-type-layout
//!
//! [Gitpod Ready-to-Code]: https://img.shields.io/badge/Gitpod-ready-blue?logo=gitpod
//! [gitpod]: https://gitpod.io/#https://github.com/juntyr/const-type-layout
//!
//! `const-type-layout-derive` provides the [`#[derive(TypeLayout)`](TypeLayout)
//! implementation for the
//! [`const_type_layout::TypeLayout`](https://docs.rs/const-type-layout/0.3/const_type_layout/trait.TypeLayout.html)
//! trait.

#![deny(clippy::complexity)]
#![deny(clippy::correctness)]
#![warn(clippy::nursery)]
#![warn(clippy::pedantic)]
#![deny(clippy::perf)]
#![deny(clippy::style)]
#![deny(clippy::suspicious)]
#![deny(missing_docs)]
#![feature(iter_intersperse)]

extern crate proc_macro;

#[macro_use]
extern crate proc_macro_error2;

use proc_macro::TokenStream;

use proc_macro2::Literal;
use quote::{quote, quote_spanned};
use syn::{parse_macro_input, spanned::Spanned};

#[proc_macro_error]
#[proc_macro_derive(TypeLayout, attributes(layout))]
/// Provides the `#[derive(TypeLayout)]` implementation for the
/// [`const_type_layout::TypeLayout`](https://docs.rs/const-type-layout/0.3/const_type_layout/trait.TypeLayout.html)
/// trait.
///
/// The derive also accepts a `#[layout(...)]` attribute to configure the
/// implementation as follows:
/// - `#[layout(crate = "<crate-path>")]` changes the path to the [`const-type-layout`](https://docs.rs/const-type-layout/0.3/const_type_layout)
///   crate that the derive uses, which by default is `const_type_layout`.
/// - `#[layout(bound = "<where-predicate>")]` adds the provided predicate to
///   the where clause of the trait implementation.
/// - `#[layout(free = "<type>")]` removes the the auto-added trait bounds for
///   the type parameter `<type>` from the trait implementation, e.g. when
///   implementing a wrapper around [`PhantomData<T>`](std::marker::PhantomData)
///   which should implement the trait for any `T`.
pub fn derive_type_layout(input: TokenStream) -> TokenStream {
    // Parse the input tokens into a syntax tree
    let input = parse_macro_input!(input as syn::DeriveInput);

    // Used in the quasi-quotation below as `#ty_name`.
    let ty_name = input.ident;
    let ty_generics = input.generics.split_for_impl().1;

    let mut type_params = input
        .generics
        .type_params()
        .map(|param| &param.ident)
        .collect::<Vec<_>>();

    let Attributes {
        reprs,
        extra_bounds,
        crate_path,
    } = parse_attributes(&input.attrs, &mut type_params);

    let inhabited = inhabited_for_type(&crate_path, &input.data);
    let layout = layout_of_type(&crate_path, &ty_name, &ty_generics, &input.data, &reprs);

    let inner_types = extract_inner_types(&input.data);

    let discriminant_ty = if let syn::Data::Enum(_) = input.data {
        Some(quote! { <Self as #crate_path::ExtractDiscriminant>::Discriminant, })
    } else {
        None
    };

    let Generics {
        type_layout_input_generics,
        type_set_input_generics,
    } = generate_generics(&crate_path, &input.generics, &extra_bounds, &type_params);
    let (type_layout_impl_generics, type_layout_ty_generics, type_layout_where_clause) =
        type_layout_input_generics.split_for_impl();
    let (type_set_impl_generics, type_set_ty_generics, type_set_where_clause) =
        type_set_input_generics.split_for_impl();

    quote! {
        unsafe impl #type_layout_impl_generics #crate_path::TypeLayout for
            #ty_name #type_layout_ty_generics #type_layout_where_clause
        {
            type Inhabited = #inhabited;

            const TYPE_LAYOUT: #crate_path::TypeLayoutInfo<'static> = {
                #crate_path::TypeLayoutInfo {
                    name: ::core::any::type_name::<Self>(),
                    size: ::core::mem::size_of::<Self>(),
                    alignment: ::core::mem::align_of::<Self>(),
                    structure: #layout,
                }
            };
        }

        unsafe impl #type_set_impl_generics #crate_path::typeset::ComputeTypeSet for
            #ty_name #type_set_ty_generics #type_set_where_clause
        {
            type Output<__TypeSetRest: #crate_path::typeset::ExpandTypeSet> =
                #crate_path::typeset::tset![
                    #(#inner_types,)* #discriminant_ty .. @ __TypeSetRest
                ];
        }
    }
    .into()
}

struct Attributes {
    reprs: String,
    extra_bounds: Vec<syn::WherePredicate>,
    crate_path: syn::Path,
}

#[allow(clippy::too_many_lines)]
fn parse_attributes(attrs: &[syn::Attribute], type_params: &mut Vec<&syn::Ident>) -> Attributes {
    // Could parse based on https://github.com/rust-lang/rust/blob/d13e8dd41d44a73664943169d5b7fe39b22c449f/compiler/rustc_attr/src/builtin.rs#L772-L781 instead
    let mut reprs = Vec::new();

    let mut extra_bounds: Vec<syn::WherePredicate> = Vec::new();

    let mut crate_path = None;

    for attr in attrs {
        if attr.path.is_ident("repr") {
            if let Ok(syn::Meta::List(syn::MetaList { nested, .. })) = attr.parse_meta() {
                for meta in nested {
                    reprs.push(match meta {
                        syn::NestedMeta::Lit(lit) => lit_to_string(&lit),
                        syn::NestedMeta::Meta(meta) => meta_to_string(&meta),
                    });
                }
            } else {
                emit_warning!(
                    attr.span(),
                    "[const-type-layout]: #[repr] attribute is not in meta list format."
                );
            }
        } else if attr.path.is_ident("layout") {
            if let Ok(syn::Meta::List(list)) = attr.parse_meta() {
                for meta in &list.nested {
                    if let syn::NestedMeta::Meta(syn::Meta::NameValue(syn::MetaNameValue {
                        path,
                        lit: syn::Lit::Str(s),
                        ..
                    })) = &meta
                    {
                        if path.is_ident("free") {
                            match syn::parse_str::<syn::Ident>(&s.value()) {
                                Ok(param) => {
                                    type_params.iter().position(|ty| **ty == param).map_or_else(
                                        || {
                                            emit_error!(
                                                s.span(),
                                                "[const-type-layout]: Invalid #[layout(free)] \
                                                 attribute: \"{}\" is either not a type parameter \
                                                 or has already been freed (duplicate attribute).",
                                                param,
                                            );
                                        },
                                        |i| {
                                            type_params.swap_remove(i);
                                        },
                                    );
                                },
                                Err(err) => emit_error!(
                                    s.span(),
                                    "[const-type-layout]: Invalid #[layout(free = \"<type>\")] \
                                     attribute: {}.",
                                    err
                                ),
                            }
                        } else if path.is_ident("bound") {
                            match syn::parse_str(&s.value()) {
                                Ok(bound) => extra_bounds.push(bound),
                                Err(err) => emit_error!(
                                    s.span(),
                                    "[const-type-layout]: Invalid #[layout(bound = \
                                     \"<where-predicate>\")] attribute: {}.",
                                    err
                                ),
                            }
                        } else if path.is_ident("crate") {
                            match syn::parse_str::<syn::Path>(&s.value()) {
                                Ok(new_crate_path) => {
                                    if crate_path.is_none() {
                                        crate_path = Some(
                                            syn::parse_quote_spanned! { s.span() => #new_crate_path },
                                        );
                                    } else {
                                        emit_error!(
                                            s.span(),
                                            "[const-type-layout]: Duplicate #[layout(crate)] \
                                             attribute: the crate path for `const-type-layout` \
                                             can only be set once per `derive`.",
                                        );
                                    }
                                },
                                Err(err) => emit_error!(
                                    s.span(),
                                    "[const-type-layout]: Invalid #[layout(crate = \
                                     \"<crate-path>\")] attribute: {}.",
                                    err
                                ),
                            }
                        } else {
                            emit_error!(
                                path.span(),
                                "[const-type-layout]: Unknown attribute, use `bound`, `crate`, or \
                                 `free`."
                            );
                        }
                    } else {
                        emit_error!(
                            meta.span(),
                            "[const-type-layout]: Expected #[layout(attr = \"value\")] syntax."
                        );
                    }
                }
            } else {
                emit_error!(
                    attr.span(),
                    "[const-type-layout]: Expected #[layout(attr = \"value\")] syntax."
                );
            }
        }
    }

    proc_macro_error2::abort_if_dirty();

    reprs.sort();
    reprs.dedup();

    let reprs = reprs
        .into_iter()
        .intersperse(String::from(","))
        .collect::<String>();

    Attributes {
        reprs,
        extra_bounds,
        crate_path: crate_path.unwrap_or_else(|| syn::parse_quote!(::const_type_layout)),
    }
}

fn meta_to_string(meta: &syn::Meta) -> String {
    match meta {
        syn::Meta::List(syn::MetaList { path, nested, .. }) => {
            let mut list = nested
                .iter()
                .map(|meta| match meta {
                    syn::NestedMeta::Lit(lit) => lit_to_string(lit),
                    syn::NestedMeta::Meta(meta) => meta_to_string(meta),
                })
                .collect::<Vec<_>>();
            list.sort();
            list.dedup();

            format!(
                "{}({})",
                quote!(#path),
                list.into_iter()
                    .intersperse(String::from(","))
                    .collect::<String>()
            )
        },
        syn::Meta::NameValue(syn::MetaNameValue { path, lit, .. }) => {
            format!("{}={}", quote!(#path), lit_to_string(lit))
        },
        syn::Meta::Path(path) => quote!(#path).to_string(),
    }
}

fn lit_to_string(lit: &syn::Lit) -> String {
    quote!(#lit).to_string().escape_default().to_string()
}

fn extract_inner_types(data: &syn::Data) -> Vec<&syn::Type> {
    let mut inner_types = Vec::new();

    match data {
        syn::Data::Struct(syn::DataStruct { fields, .. }) => {
            for field in fields {
                inner_types.push(&field.ty);
            }
        },
        syn::Data::Union(syn::DataUnion {
            fields: syn::FieldsNamed { named: fields, .. },
            ..
        }) => {
            for field in fields {
                inner_types.push(&field.ty);
            }
        },
        syn::Data::Enum(syn::DataEnum { variants, .. }) => {
            for variant in variants {
                for field in &variant.fields {
                    inner_types.push(&field.ty);
                }
            }
        },
    }

    inner_types
}

struct Generics {
    type_layout_input_generics: syn::Generics,
    type_set_input_generics: syn::Generics,
}

fn generate_generics(
    crate_path: &syn::Path,
    generics: &syn::Generics,
    extra_bounds: &[syn::WherePredicate],
    type_params: &[&syn::Ident],
) -> Generics {
    let mut type_layout_input_generics = generics.clone();
    let mut type_set_input_generics = generics.clone();

    for ty in type_params {
        type_layout_input_generics
            .make_where_clause()
            .predicates
            .push(syn::parse_quote! {
                #ty: #crate_path::TypeLayout
            });

        type_set_input_generics
            .make_where_clause()
            .predicates
            .push(syn::parse_quote! {
                #ty: #crate_path::typeset::ComputeTypeSet
            });
    }

    for bound in extra_bounds {
        type_layout_input_generics
            .make_where_clause()
            .predicates
            .push(bound.clone());

        type_set_input_generics
            .make_where_clause()
            .predicates
            .push(bound.clone());
    }

    Generics {
        type_layout_input_generics,
        type_set_input_generics,
    }
}

fn layout_of_type(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    data: &syn::Data,
    reprs: &str,
) -> proc_macro2::TokenStream {
    match data {
        syn::Data::Struct(data) => {
            let fields = quote_structlike_fields(crate_path, ty_name, ty_generics, &data.fields);

            quote! {
                #crate_path::TypeStructure::Struct { repr: #reprs, fields: &[#(#fields),*] }
            }
        },
        syn::Data::Enum(r#enum) => {
            let variants = quote_enum_variants(crate_path, ty_name, ty_generics, r#enum);

            quote! {
                #crate_path::TypeStructure::Enum { repr: #reprs, variants: &[#(#variants),*] }
            }
        },
        syn::Data::Union(union) => {
            let fields = quote_structlike_fields(
                crate_path,
                ty_name,
                ty_generics,
                &syn::Fields::Named(union.fields.clone()),
            );

            quote! {
                #crate_path::TypeStructure::Union { repr: #reprs, fields: &[#(#fields),*] }
            }
        },
    }
}

fn quote_structlike_fields(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    fields: &syn::Fields,
) -> Vec<proc_macro2::TokenStream> {
    match fields {
        syn::Fields::Named(fields) => fields
            .named
            .iter()
            .map(|field| {
                let field_name = field.ident.as_ref().unwrap();
                let field_name_str = Literal::string(&field_name.to_string());
                let field_ty = &field.ty;
                let field_offset = quote_structlike_field_offset(
                    crate_path,
                    ty_name,
                    ty_generics,
                    &field_name,
                    field_ty,
                );

                quote_spanned! { field.span() =>
                    #crate_path::Field {
                        name: #field_name_str,
                        offset: { #field_offset },
                        ty: ::core::any::type_name::<#field_ty>(),
                    }
                }
            })
            .collect(),
        syn::Fields::Unnamed(fields) => fields
            .unnamed
            .iter()
            .enumerate()
            .map(|(field_index, field)| {
                let field_name = syn::Index::from(field_index);
                let field_name_str = Literal::string(&field_index.to_string());
                let field_ty = &field.ty;
                let field_offset = quote_structlike_field_offset(
                    crate_path,
                    ty_name,
                    ty_generics,
                    &field_name,
                    field_ty,
                );

                quote_spanned! { field.span() =>
                    #crate_path::Field {
                        name: #field_name_str,
                        offset: { #field_offset },
                        ty: ::core::any::type_name::<#field_ty>(),
                    }
                }
            })
            .collect(),
        syn::Fields::Unit => vec![],
    }
}

fn quote_structlike_field_offset(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    field_name: &impl quote::ToTokens,
    field_ty: &syn::Type,
) -> proc_macro2::TokenStream {
    quote! {
        #crate_path::MaybeUninhabited::new::<#field_ty>(
            ::core::mem::offset_of!(#ty_name #ty_generics, #field_name)
        )
    }
}

fn quote_enum_variants(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    r#enum: &syn::DataEnum,
) -> Vec<proc_macro2::TokenStream> {
    let mut last_discriminant = syn::Expr::Lit(syn::ExprLit {
        attrs: vec![],
        lit: syn::Lit::Int(syn::LitInt::from(proc_macro2::Literal::usize_unsuffixed(0))),
    });
    let mut last_discriminant_offset = 0;

    r#enum
        .variants
        .iter()
        .map(|variant| {
            let variant_name = &variant.ident;
            let variant_name_str = Literal::string(&variant_name.to_string());

            let fields = quote_variant_fields(
                crate_path,
                ty_name,
                ty_generics,
                variant_name,
                &variant.fields,
            );

            let discriminant = match variant.discriminant.as_ref() {
                None => {
                    let discriminant = syn::Expr::Binary(syn::ExprBinary {
                        attrs: vec![],
                        left: Box::new(last_discriminant.clone()),
                        op: syn::parse_quote!(+),
                        right: Box::new(syn::Expr::Lit(syn::ExprLit {
                            attrs: vec![],
                            lit: syn::Lit::Int(syn::LitInt::from(
                                proc_macro2::Literal::usize_unsuffixed(last_discriminant_offset),
                            )),
                        })),
                    });
                    last_discriminant_offset += 1;
                    discriminant
                },
                Some((_, discriminant)) => {
                    last_discriminant = discriminant.clone();
                    last_discriminant_offset = 0;
                    discriminant.clone()
                },
            };

            // Variants are inhabited if all of their fields in inhabited
            let variant_inhabited = match &variant.fields {
                syn::Fields::Named(syn::FieldsNamed { named: fields, .. })
                | syn::Fields::Unnamed(syn::FieldsUnnamed {
                    unnamed: fields, ..
                }) => {
                    let field_tys = fields.iter().map(|syn::Field { ty, .. }| ty);

                    quote! { #crate_path::inhabited::all![#(#field_tys),*] }
                },
                syn::Fields::Unit => quote! { #crate_path::inhabited::Inhabited },
            };

            let discriminant = quote! {
                #crate_path::MaybeUninhabited::new::<#variant_inhabited>(
                    #crate_path::Discriminant::new::<Self>(#discriminant)
                )
            };

            quote! {
                #crate_path::Variant {
                    name: #variant_name_str,
                    discriminant: #discriminant,
                    fields: &[#(#fields),*],
                }
            }
        })
        .collect::<Vec<_>>()
}

fn quote_variant_fields(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    variant_name: &syn::Ident,
    variant_fields: &syn::Fields,
) -> Vec<proc_macro2::TokenStream> {
    match variant_fields {
        syn::Fields::Named(syn::FieldsNamed { named: fields, .. }) => fields
            .iter()
            .map(|field| {
                let field_name_str = Literal::string(&field.ident.as_ref().unwrap().to_string());
                let field_name = &field.ident;
                let field_ty = &field.ty;

                let offset = quote_structlike_variant_field_offset(
                    crate_path,
                    ty_name,
                    ty_generics,
                    variant_name,
                    field_name,
                    field_ty,
                );

                quote_spanned! { field.span() =>
                    #crate_path::Field {
                        name: #field_name_str,
                        offset: #offset,
                        ty: ::core::any::type_name::<#field_ty>(),
                    }
                }
            })
            .collect(),
        syn::Fields::Unnamed(syn::FieldsUnnamed {
            unnamed: fields, ..
        }) => fields
            .iter()
            .enumerate()
            .map(|(field_index, field)| {
                let field_name_str = Literal::string(&field_index.to_string());
                let field_index = syn::Index::from(field_index);
                let field_ty = &field.ty;

                let offset = quote_structlike_variant_field_offset(
                    crate_path,
                    ty_name,
                    ty_generics,
                    variant_name,
                    &field_index,
                    field_ty,
                );

                quote_spanned! { field.span() =>
                    #crate_path::Field {
                        name: #field_name_str,
                        offset: #offset,
                        ty: ::core::any::type_name::<#field_ty>(),
                    }
                }
            })
            .collect(),
        syn::Fields::Unit => vec![],
    }
}

fn quote_structlike_variant_field_offset(
    crate_path: &syn::Path,
    ty_name: &syn::Ident,
    ty_generics: &syn::TypeGenerics,
    variant_name: &syn::Ident,
    field_name: &impl quote::ToTokens,
    field_ty: &syn::Type,
) -> proc_macro2::TokenStream {
    quote! {
        #crate_path::MaybeUninhabited::new::<#field_ty>(
            ::core::mem::offset_of!(#ty_name #ty_generics, #variant_name.#field_name)
        )
    }
}

fn inhabited_for_type(crate_path: &syn::Path, data: &syn::Data) -> proc_macro2::TokenStream {
    match data {
        syn::Data::Struct(data) => {
            // Structs are inhabited if all of their fields in inhabited
            let fields = match &data.fields {
                syn::Fields::Named(syn::FieldsNamed { named: fields, .. })
                | syn::Fields::Unnamed(syn::FieldsUnnamed {
                    unnamed: fields, ..
                }) => fields,
                syn::Fields::Unit => return quote! { #crate_path::inhabited::Inhabited },
            };

            let field_tys = fields.iter().map(|syn::Field { ty, .. }| ty);

            quote! { #crate_path::inhabited::all![#(#field_tys),*] }
        },
        syn::Data::Enum(syn::DataEnum { variants, .. }) => {
            let variants_inhabited = variants.iter().map(|syn::Variant { fields, .. }| {
                // Variants are inhabited if all of their fields in inhabited
                let fields = match fields {
                    syn::Fields::Named(syn::FieldsNamed { named: fields, .. })
                    | syn::Fields::Unnamed(syn::FieldsUnnamed {
                        unnamed: fields, ..
                    }) => fields,
                    syn::Fields::Unit => return quote! { #crate_path::inhabited::Inhabited },
                };

                let field_tys = fields.iter().map(|syn::Field { ty, .. }| ty);

                quote! { #crate_path::inhabited::all![#(#field_tys),*] }
            });

            // Enums are inhabited if they have at least one inhabited variant
            quote! {
                #crate_path::inhabited::any![#(#variants_inhabited),*]
            }
        },
        syn::Data::Union(syn::DataUnion {
            fields: syn::FieldsNamed { named: fields, .. },
            ..
        }) => {
            // Unions are inhabited if they have at least one inhabited field
            let field_tys = fields.iter().map(|syn::Field { ty, .. }| ty);

            quote! { #crate_path::inhabited::any![#(#field_tys),*] }
        },
    }
}