ploidy-codegen-rust 0.10.0

A Ploidy generator that emits Rust code
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
use std::{
    borrow::{Borrow, Cow},
    cmp::Ordering,
    fmt::Display,
    ops::Deref,
};

use heck::{AsKebabCase, AsPascalCase, AsSnekCase};
use itertools::Itertools;
use ploidy_core::{
    codegen::{
        UniqueNames,
        unique::{UniqueNamesScope, WordSegments},
    },
    ir::{
        ExtendableView, InlineTypePathSegment, InlineTypeView, PrimitiveType, SchemaTypeView,
        StructFieldName, StructFieldNameHint, UntaggedVariantNameHint,
    },
};
use proc_macro2::{Ident, Span, TokenStream};
use quote::{IdentFragment, ToTokens, TokenStreamExt};
use ref_cast::{RefCastCustom, ref_cast_custom};

// Keywords that can't be used as identifiers, even with `r#`.
const KEYWORDS: &[&str] = &["crate", "self", "super", "Self"];

/// A name for a schema or an inline type, used in generated Rust code.
///
/// [`CodegenTypeName`] is the high-level representation of a type name.
/// For emitting arbitrary identifiers, like fields, parameters, and methods,
/// use [`CodegenIdent`] and [`CodegenIdentUsage`] instead.
///
/// [`CodegenTypeName`] implements [`ToTokens`] to produce PascalCase identifiers
/// (e.g., `Pet`, `GetItemsFilter`) in [`quote`] macros.
/// Use [`into_module_name`](Self::into_module_name) for the corresponding module name,
/// and [`into_sort_key`](Self::into_sort_key) for deterministic sorting.
#[derive(Clone, Copy, Debug)]
pub enum CodegenTypeName<'a> {
    Schema(&'a SchemaTypeView<'a>),
    Inline(&'a InlineTypeView<'a>),
}

impl<'a> CodegenTypeName<'a> {
    #[inline]
    pub fn into_module_name(self) -> CodegenModuleName<'a> {
        CodegenModuleName(self)
    }

    #[inline]
    pub fn into_sort_key(self) -> CodegenTypeNameSortKey<'a> {
        CodegenTypeNameSortKey(self)
    }
}

impl ToTokens for CodegenTypeName<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self {
            Self::Schema(view) => {
                let ident = view.extensions().get::<CodegenIdent>().unwrap();
                CodegenIdentUsage::Type(&ident).to_tokens(tokens);
            }
            Self::Inline(view) => {
                let ident = CodegenIdent::from_segments(view.path().segments);
                CodegenIdentUsage::Type(&ident).to_tokens(tokens);
            }
        }
    }
}

/// A module name derived from a [`CodegenTypeName`].
///
/// Implements [`ToTokens`] to produce a snake_case identifier. For
/// string interpolation (e.g., file paths), use [`display`](Self::display),
/// which returns an `impl Display` that can be used with `format!`.
#[derive(Clone, Copy, Debug)]
pub struct CodegenModuleName<'a>(CodegenTypeName<'a>);

impl<'a> CodegenModuleName<'a> {
    #[inline]
    pub fn into_type_name(self) -> CodegenTypeName<'a> {
        self.0
    }

    /// Returns a formattable representation of this module name.
    ///
    /// [`CodegenModuleName`] doesn't implement [`Display`] directly, to help catch
    /// context mismatches: using `.display()` in a [`quote`] macro, or
    /// `.to_token_stream()` in a [`format`] string, stands out during review.
    pub fn display(&self) -> impl Display {
        struct DisplayModuleName<'a>(CodegenTypeName<'a>);
        impl Display for DisplayModuleName<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self.0 {
                    CodegenTypeName::Schema(view) => {
                        let ident = view.extensions().get::<CodegenIdent>().unwrap();
                        write!(f, "{}", CodegenIdentUsage::Module(&ident).display())
                    }
                    CodegenTypeName::Inline(view) => {
                        let ident = CodegenIdent::from_segments(view.path().segments);
                        write!(f, "{}", CodegenIdentUsage::Module(&ident).display())
                    }
                }
            }
        }
        DisplayModuleName(self.0)
    }
}

impl ToTokens for CodegenModuleName<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match self.0 {
            CodegenTypeName::Schema(view) => {
                let ident = view.extensions().get::<CodegenIdent>().unwrap();
                CodegenIdentUsage::Module(&ident).to_tokens(tokens);
            }
            CodegenTypeName::Inline(view) => {
                let ident = CodegenIdent::from_segments(view.path().segments);
                CodegenIdentUsage::Module(&ident).to_tokens(tokens);
            }
        }
    }
}

/// A sort key for deterministic ordering of [`CodegenTypeName`]s.
///
/// Sorts schema types before inline types, then lexicographically by name.
/// This ensures that code generation produces stable output regardless of
/// declaration order.
#[derive(Clone, Copy, Debug)]
pub struct CodegenTypeNameSortKey<'a>(CodegenTypeName<'a>);

impl<'a> CodegenTypeNameSortKey<'a> {
    #[inline]
    pub fn for_schema(view: &'a SchemaTypeView<'a>) -> Self {
        Self(CodegenTypeName::Schema(view))
    }

    #[inline]
    pub fn for_inline(view: &'a InlineTypeView<'a>) -> Self {
        Self(CodegenTypeName::Inline(view))
    }

    #[inline]
    pub fn into_name(self) -> CodegenTypeName<'a> {
        self.0
    }
}

impl Eq for CodegenTypeNameSortKey<'_> {}

impl Ord for CodegenTypeNameSortKey<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        match (&self.0, &other.0) {
            (CodegenTypeName::Schema(a), CodegenTypeName::Schema(b)) => a.name().cmp(b.name()),
            (CodegenTypeName::Inline(a), CodegenTypeName::Inline(b)) => a.path().cmp(&b.path()),
            (CodegenTypeName::Schema(_), CodegenTypeName::Inline(_)) => Ordering::Less,
            (CodegenTypeName::Inline(_), CodegenTypeName::Schema(_)) => Ordering::Greater,
        }
    }
}

impl PartialEq for CodegenTypeNameSortKey<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other).is_eq()
    }
}

impl PartialOrd for CodegenTypeNameSortKey<'_> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// A string that's statically guaranteed to be valid for any
/// [`CodegenIdentUsage`].
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct CodegenIdent(String);

impl CodegenIdent {
    /// Creates an identifier for any usage.
    pub fn new(s: &str) -> Self {
        let s = clean(s);
        if KEYWORDS.contains(&s.as_str()) {
            Self(format!("_{s}"))
        } else {
            Self(s)
        }
    }

    /// Creates an identifier from an inline type path.
    pub fn from_segments(segments: &[InlineTypePathSegment<'_>]) -> Self {
        Self(format!(
            "{}",
            segments
                .iter()
                .map(CodegenTypePathSegment)
                .format_with("", |segment, f| f(&segment.display()))
        ))
    }
}

impl AsRef<CodegenIdentRef> for CodegenIdent {
    fn as_ref(&self) -> &CodegenIdentRef {
        self
    }
}

impl Borrow<CodegenIdentRef> for CodegenIdent {
    fn borrow(&self) -> &CodegenIdentRef {
        self
    }
}

impl Deref for CodegenIdent {
    type Target = CodegenIdentRef;

    fn deref(&self) -> &Self::Target {
        CodegenIdentRef::new(&self.0)
    }
}

/// A string slice that's guaranteed to be valid for any [`CodegenIdentUsage`].
#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, RefCastCustom)]
#[repr(transparent)]
pub struct CodegenIdentRef(str);

impl CodegenIdentRef {
    #[ref_cast_custom]
    fn new(s: &str) -> &Self;

    /// Returns a suitable identifier for a struct field that
    /// doesn't have an explicit name in the spec.
    pub fn from_field_name_hint(hint: StructFieldNameHint) -> Cow<'static, Self> {
        match hint {
            StructFieldNameHint::Index(index) => {
                Cow::Owned(CodegenIdent(format!("variant_{index}")))
            }
            StructFieldNameHint::AdditionalProperties => {
                Cow::Borrowed(Self::new("additional_properties"))
            }
        }
    }
}

impl ToOwned for CodegenIdentRef {
    type Owned = CodegenIdent;

    fn to_owned(&self) -> Self::Owned {
        CodegenIdent(self.0.to_owned())
    }
}

/// A Cargo feature for conditionally compiling generated code.
///
/// Feature names appear in the `Cargo.toml` `[features]` table,
/// and in `#[cfg(feature = "...")]` attributes. The special `default` feature
/// enables all other features.
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum CargoFeature {
    #[default]
    Default,
    Named(CodegenIdent),
}

impl CargoFeature {
    #[inline]
    pub fn from_name(name: &str) -> Self {
        match name {
            // `default` can't be used as a literal feature name; ignore it.
            "default" => Self::Default,

            // Cargo and crates.io limit which characters can appear in feature names;
            // further, we use feature names as module names for operations, so
            // the feature name needs to be usable as a Rust identifier.
            name => Self::Named(CodegenIdent::new(name)),
        }
    }

    #[inline]
    pub fn as_ident(&self) -> &CodegenIdentRef {
        match self {
            Self::Named(name) => name,
            Self::Default => CodegenIdentRef::new("default"),
        }
    }

    #[inline]
    pub fn display(&self) -> impl Display {
        match self {
            Self::Named(name) => AsKebabCase(name.0.as_str()),
            Self::Default => AsKebabCase("default"),
        }
    }
}

/// A context-aware wrapper for emitting a [`CodegenIdentRef`] as a Rust identifier.
///
/// [`CodegenIdentUsage`] is a lower-level building block for generating
/// identifiers. For schema and inline types, prefer [`CodegenTypeName`] instead.
///
/// Each [`CodegenIdentUsage`] variant determines the case transformation
/// applied to the identifier: module, field, parameter, and method names
/// become snake_case; type and enum variant names become PascalCase.
///
/// Implements [`ToTokens`] for use in [`quote`] macros. For string interpolation,
/// use [`display`](Self::display).
#[derive(Clone, Copy, Debug)]
pub enum CodegenIdentUsage<'a> {
    Module(&'a CodegenIdentRef),
    Type(&'a CodegenIdentRef),
    Field(&'a CodegenIdentRef),
    Variant(&'a CodegenIdentRef),
    Param(&'a CodegenIdentRef),
    Method(&'a CodegenIdentRef),
}

impl CodegenIdentUsage<'_> {
    /// Returns a formattable representation of this identifier.
    ///
    /// [`CodegenIdentUsage`] doesn't implement [`Display`] directly, to help catch
    /// context mismatches: using `.display()` in a [`quote`] macro, or
    /// `.to_token_stream()` in a [`format`] string, stands out during review.
    pub fn display(self) -> impl Display {
        struct DisplayUsage<'a>(CodegenIdentUsage<'a>);
        impl Display for DisplayUsage<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use CodegenIdentUsage::*;
                match self.0 {
                    Module(name) | Field(name) | Param(name) | Method(name) => {
                        if name.0.starts_with(unicode_ident::is_xid_start) {
                            write!(f, "{}", AsSnekCase(&name.0))
                        } else {
                            // `name` doesn't start with `XID_Start` (e.g., "1099KStatus"),
                            // so prefix it with `_`; everything after is known to be
                            // `XID_Continue`.
                            write!(f, "_{}", AsSnekCase(&name.0))
                        }
                    }
                    Type(name) | Variant(name) => {
                        if name.0.starts_with(unicode_ident::is_xid_start) {
                            write!(f, "{}", AsPascalCase(&name.0))
                        } else {
                            write!(f, "_{}", AsPascalCase(&name.0))
                        }
                    }
                }
            }
        }
        DisplayUsage(self)
    }
}

impl IdentFragment for CodegenIdentUsage<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.display())
    }
}

impl ToTokens for CodegenIdentUsage<'_> {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let s = self.display().to_string();
        let ident = syn::parse_str(&s).unwrap_or_else(|_| Ident::new_raw(&s, Span::call_site()));
        tokens.append(ident);
    }
}

/// A scope for generating unique, valid Rust identifiers.
#[derive(Debug)]
pub struct CodegenIdentScope<'a>(UniqueNamesScope<'a>);

impl<'a> CodegenIdentScope<'a> {
    /// Creates a new identifier scope that's backed by the given arena.
    pub fn new(arena: &'a UniqueNames) -> Self {
        Self::with_reserved(arena, &[])
    }

    /// Creates a new identifier scope that's backed by the given arena,
    /// with additional pre-reserved names.
    pub fn with_reserved(arena: &'a UniqueNames, reserved: &[&str]) -> Self {
        Self(arena.scope_with_reserved(itertools::chain!(
            reserved.iter().copied(),
            KEYWORDS.iter().copied(),
            std::iter::once("")
        )))
    }

    /// Cleans the input string and returns a name that's unique
    /// within this scope, and valid for any [`CodegenIdentUsage`].
    pub fn uniquify(&mut self, name: &str) -> CodegenIdent {
        CodegenIdent(self.0.uniquify(&clean(name)).into_owned())
    }
}

#[derive(Clone, Copy, Debug)]
pub struct CodegenUntaggedVariantName(pub UntaggedVariantNameHint);

impl ToTokens for CodegenUntaggedVariantName {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        use UntaggedVariantNameHint::*;
        let s = match self.0 {
            Primitive(PrimitiveType::String) => "String".into(),
            Primitive(PrimitiveType::I8) => "I8".into(),
            Primitive(PrimitiveType::U8) => "U8".into(),
            Primitive(PrimitiveType::I16) => "I16".into(),
            Primitive(PrimitiveType::U16) => "U16".into(),
            Primitive(PrimitiveType::I32) => "I32".into(),
            Primitive(PrimitiveType::U32) => "U32".into(),
            Primitive(PrimitiveType::I64) => "I64".into(),
            Primitive(PrimitiveType::U64) => "U64".into(),
            Primitive(PrimitiveType::F32) => "F32".into(),
            Primitive(PrimitiveType::F64) => "F64".into(),
            Primitive(PrimitiveType::Bool) => "Bool".into(),
            Primitive(PrimitiveType::DateTime) => "DateTime".into(),
            Primitive(PrimitiveType::UnixTime) => "UnixTime".into(),
            Primitive(PrimitiveType::Date) => "Date".into(),
            Primitive(PrimitiveType::Url) => "Url".into(),
            Primitive(PrimitiveType::Uuid) => "Uuid".into(),
            Primitive(PrimitiveType::Bytes) => "Bytes".into(),
            Primitive(PrimitiveType::Binary) => "Binary".into(),
            Array => "Array".into(),
            Map => "Map".into(),
            Index(index) => Cow::Owned(format!("V{index}")),
        };
        tokens.append(Ident::new(&s, Span::call_site()));
    }
}

#[derive(Clone, Copy, Debug)]
pub struct CodegenTypePathSegment<'a>(&'a InlineTypePathSegment<'a>);

impl<'a> CodegenTypePathSegment<'a> {
    pub fn display(&self) -> impl Display {
        struct DisplaySegment<'a>(&'a InlineTypePathSegment<'a>);
        impl Display for DisplaySegment<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                use InlineTypePathSegment::*;
                match self.0 {
                    // Segments are always part of an identifier, never emitted directly;
                    // so we don't need to check for `XID_Start`.
                    Operation(name) => write!(f, "{}", AsPascalCase(clean(name))),
                    Parameter(name) => write!(f, "{}", AsPascalCase(clean(name))),
                    Request => f.write_str("Request"),
                    Response => f.write_str("Response"),
                    Field(StructFieldName::Name(name)) => {
                        write!(f, "{}", AsPascalCase(clean(name)))
                    }
                    Field(StructFieldName::Hint(StructFieldNameHint::Index(index))) => {
                        write!(f, "Variant{index}")
                    }
                    Field(StructFieldName::Hint(StructFieldNameHint::AdditionalProperties)) => {
                        f.write_str("AdditionalProperties")
                    }
                    MapValue => f.write_str("Value"),
                    ArrayItem => f.write_str("Item"),
                    Variant(index) => write!(f, "V{index}"),
                    Parent(index) => write!(f, "P{index}"),
                    TaggedVariant(name) => write!(f, "{}", AsPascalCase(clean(name))),
                }
            }
        }
        DisplaySegment(self.0)
    }
}

/// Makes a string suitable for inclusion within a Rust identifier.
///
/// Cleaning segments the string on word boundaries, collapses all
/// non-`XID_Continue` characters into new boundaries, and
/// reassembles the string. This makes the string resilient to
/// case transformations, which also collapse boundaries, and so
/// can produce duplicates in some cases.
///
/// Note that the result may not itself be a valid Rust identifier,
/// because Rust identifiers must start with `XID_Start`.
/// This is checked and handled in [`CodegenIdentUsage`].
fn clean(s: &str) -> String {
    WordSegments::new(s)
        .flat_map(|s| s.split(|c| !unicode_ident::is_xid_continue(c)))
        .join("_")
}

#[cfg(test)]
mod tests {
    use super::*;

    use pretty_assertions::assert_eq;
    use syn::parse_quote;

    // MARK: Cargo features

    #[test]
    fn test_feature_from_name() {
        let feature = CargoFeature::from_name("customers");
        assert_eq!(feature.display().to_string(), "customers");
    }

    #[test]
    fn test_feature_default() {
        let feature = CargoFeature::Default;
        assert_eq!(feature.display().to_string(), "default");

        let feature = CargoFeature::from_name("default");
        assert_eq!(feature, CargoFeature::Default);
    }

    #[test]
    fn test_features_from_multiple_words() {
        let feature = CargoFeature::from_name("foo_bar");
        assert_eq!(feature.display().to_string(), "foo-bar");

        let feature = CargoFeature::from_name("foo.bar");
        assert_eq!(feature.display().to_string(), "foo-bar");

        let feature = CargoFeature::from_name("fooBar");
        assert_eq!(feature.display().to_string(), "foo-bar");

        let feature = CargoFeature::from_name("FooBar");
        assert_eq!(feature.display().to_string(), "foo-bar");
    }

    // MARK: Usages

    #[test]
    fn test_codegen_ident_type() {
        let ident = CodegenIdent::new("pet_store");
        let usage = CodegenIdentUsage::Type(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(PetStore);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_field() {
        let ident = CodegenIdent::new("petStore");
        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(pet_store);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_module() {
        let ident = CodegenIdent::new("MyModule");
        let usage = CodegenIdentUsage::Module(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(my_module);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_variant() {
        let ident = CodegenIdent::new("http_error");
        let usage = CodegenIdentUsage::Variant(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(HttpError);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_param() {
        let ident = CodegenIdent::new("userId");
        let usage = CodegenIdentUsage::Param(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(user_id);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_method() {
        let ident = CodegenIdent::new("getUserById");
        let usage = CodegenIdentUsage::Method(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(get_user_by_id);
        assert_eq!(actual, expected);
    }

    // MARK: Special characters

    #[test]
    fn test_codegen_ident_handles_rust_keywords() {
        let ident = CodegenIdent::new("type");
        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(r#type);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_handles_invalid_start_chars() {
        let ident = CodegenIdent::new("123foo");
        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(_123_foo);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_handles_special_chars() {
        let ident = CodegenIdent::new("foo-bar-baz");
        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(foo_bar_baz);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_codegen_ident_handles_number_prefix() {
        let ident = CodegenIdent::new("1099KStatus");

        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(_1099_k_status);
        assert_eq!(actual, expected);

        let usage = CodegenIdentUsage::Type(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(_1099KStatus);
        assert_eq!(actual, expected);
    }

    // MARK: Untagged variant names

    #[test]
    fn test_untagged_variant_name_string() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::String));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(String);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_i32() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::I32));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(I32);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_i64() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::I64));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(I64);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_f32() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::F32));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(F32);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_f64() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::F64));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(F64);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_bool() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::Bool));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Bool);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_datetime() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::DateTime));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(DateTime);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_date() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::Date));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Date);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_url() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::Url));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Url);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_uuid() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::Uuid));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Uuid);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_bytes() {
        let variant_name =
            CodegenUntaggedVariantName(UntaggedVariantNameHint::Primitive(PrimitiveType::Bytes));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Bytes);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_index() {
        let variant_name = CodegenUntaggedVariantName(UntaggedVariantNameHint::Index(0));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(V0);
        assert_eq!(actual, expected);

        let variant_name = CodegenUntaggedVariantName(UntaggedVariantNameHint::Index(42));
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(V42);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_array() {
        let variant_name = CodegenUntaggedVariantName(UntaggedVariantNameHint::Array);
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Array);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_untagged_variant_name_map() {
        let variant_name = CodegenUntaggedVariantName(UntaggedVariantNameHint::Map);
        let actual: syn::Ident = parse_quote!(#variant_name);
        let expected: syn::Ident = parse_quote!(Map);
        assert_eq!(actual, expected);
    }

    // MARK: Struct field names

    #[test]
    fn test_struct_field_name_index() {
        let field_name = CodegenIdentRef::from_field_name_hint(StructFieldNameHint::Index(0));
        let usage = CodegenIdentUsage::Field(&field_name);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(variant_0);
        assert_eq!(actual, expected);

        let field_name = CodegenIdentRef::from_field_name_hint(StructFieldNameHint::Index(5));
        let usage = CodegenIdentUsage::Field(&field_name);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(variant_5);
        assert_eq!(actual, expected);
    }

    #[test]
    fn test_struct_field_name_additional_properties() {
        let field_name =
            CodegenIdentRef::from_field_name_hint(StructFieldNameHint::AdditionalProperties);
        let usage = CodegenIdentUsage::Field(&field_name);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(additional_properties);
        assert_eq!(actual, expected);
    }

    // MARK: `clean()`

    #[test]
    fn test_clean() {
        assert_eq!(clean("foo-bar"), "foo_bar");
        assert_eq!(clean("foo.bar"), "foo_bar");
        assert_eq!(clean("foo bar"), "foo_bar");
        assert_eq!(clean("foo@bar"), "foo_bar");
        assert_eq!(clean("foo#bar"), "foo_bar");
        assert_eq!(clean("foo!bar"), "foo_bar");

        assert_eq!(clean("foo_bar"), "foo_bar");
        assert_eq!(clean("FooBar"), "Foo_Bar");
        assert_eq!(clean("foo123"), "foo123");
        assert_eq!(clean("_foo"), "foo");

        assert_eq!(clean("_foo"), "foo");
        assert_eq!(clean("__foo"), "foo");

        // Digits are in `XID_Continue`, so they should be preserved.
        assert_eq!(clean("123foo"), "123_foo");
        assert_eq!(clean("9bar"), "9_bar");

        // Non-ASCII characters that are valid in identifiers should be preserved;
        // characters that aren't should be replaced.
        assert_eq!(clean("café"), "café");
        assert_eq!(clean("foo™bar"), "foo_bar");

        // Invalid characters should be collapsed.
        assert_eq!(clean("foo---bar"), "foo_bar");
        assert_eq!(clean("foo...bar"), "foo_bar");
    }

    // MARK: Scopes

    #[test]
    fn test_codegen_ident_scope_handles_empty() {
        let unique = UniqueNames::new();
        let mut scope = CodegenIdentScope::new(&unique);
        let ident = scope.uniquify("");

        let usage = CodegenIdentUsage::Field(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(_2);
        assert_eq!(actual, expected);

        let usage = CodegenIdentUsage::Type(&ident);
        let actual: syn::Ident = parse_quote!(#usage);
        let expected: syn::Ident = parse_quote!(_2);
        assert_eq!(actual, expected);
    }
}