reallyme-buffa-codegen 0.1.2

ReallyMe fork: Shared code generation logic for buffa (descriptor → Rust source)
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
// Modified by ReallyMe Technologies Limited.
//! Enum type code generation.

use std::collections::HashMap;

use crate::generated::descriptor::EnumDescriptorProto;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};

use crate::context::CodeGenContext;
use crate::features::ResolvedFeatures;
use crate::CodeGenError;

/// Generate custom `Serialize` and `Deserialize` impls for a proto enum.
///
/// - Serialize: emits the proto name string via `Enumeration::proto_name`.
/// - Deserialize: accepts a string (via `from_proto_name`), an integer (via
///   `from_i32`), or null (→ `Default::default()`). Unknown values produce
///   a hard error — lenient handling happens at the field-level serde helpers.
fn generate_enum_serde(name_ident: &Ident) -> TokenStream {
    quote! {
        impl ::serde::Serialize for #name_ident {
            fn serialize<__S: ::serde::Serializer>(&self, s: __S) -> ::core::result::Result<__S::Ok, __S::Error> {
                s.serialize_str(::buffa::Enumeration::proto_name(self))
            }
        }

        impl<'de> ::serde::Deserialize<'de> for #name_ident {
            fn deserialize<__D: ::serde::Deserializer<'de>>(d: __D) -> ::core::result::Result<Self, __D::Error> {
                ::buffa::json_helpers::closed_enum::deserialize_strict(d)
            }
        }

        impl ::buffa::json_helpers::ProtoElemJson for #name_ident {
            fn serialize_proto_json<__S: ::serde::Serializer>(
                v: &Self,
                s: __S,
            ) -> ::core::result::Result<__S::Ok, __S::Error> {
                ::serde::Serialize::serialize(v, s)
            }
            fn deserialize_proto_json<'de, __D: ::serde::Deserializer<'de>>(
                d: __D,
            ) -> ::core::result::Result<Self, __D::Error> {
                <Self as ::serde::Deserialize>::deserialize(d)
            }
        }
    }
}

/// True when the enum value carries `[deprecated = true]`.
fn is_deprecated_value(value: &crate::generated::descriptor::EnumValueDescriptorProto) -> bool {
    value
        .options
        .as_option()
        .and_then(|o| o.deprecated)
        .unwrap_or(false)
}

/// For each value of `enum_desc`, in declaration order, whether its generated
/// item carries `#[deprecated]`.
///
/// The first value declared for a number is the variant, which is deprecated
/// by its own option. A later value with that number is an alias `const`,
/// which is deprecated by its own option or by its variant's: an alias is
/// another name for the variant, so it must not be a way around the marker.
pub(crate) fn deprecated_items(enum_desc: &EnumDescriptorProto) -> Vec<bool> {
    let mut variant_deprecated: HashMap<i32, bool> = HashMap::new();
    enum_desc
        .value
        .iter()
        .map(|v| {
            let own = is_deprecated_value(v);
            let inherited = v
                .number
                .is_some_and(|number| *variant_deprecated.entry(number).or_insert(own));
            own || inherited
        })
        .collect()
}

/// Generate Rust code for a protobuf enum type.
///
/// `rust_name` is the Rust identifier to use.  For top-level enums this is
/// the proto enum name; for nested enums it is the parent-prefixed flat name
/// (e.g. `TestAllTypesProto3NestedEnum`) matching the type-map convention.
pub fn generate_enum(
    ctx: &CodeGenContext,
    enum_desc: &EnumDescriptorProto,
    rust_name: &str,
    proto_fqn: &str,
    features: &ResolvedFeatures,
    _resolver: &crate::imports::ImportResolver,
) -> Result<TokenStream, CodeGenError> {
    let name_ident = format_ident!("{}", rust_name);
    // Enum declarations can override an editions file's default openness.
    // Reflection must agree with field typing, which resolves this same override.
    let enum_features =
        crate::features::resolve_child(features, crate::features::enum_features(enum_desc));

    // Track which discriminant values have been seen to identify aliases.
    // Proto spec: the first value with a given number is the primary; subsequent
    // values with the same number (requires allow_alias = true in enum options)
    // are aliases.  Rust #[repr(i32)] enums cannot have duplicate discriminants,
    // so aliases are emitted as `pub const` items instead of enum variants.
    let mut seen: HashMap<i32, &str> = HashMap::new();
    let mut variants = Vec::new();
    let mut alias_consts = Vec::new();
    let mut from_i32_arms = Vec::new();
    let mut from_proto_name_arms: Vec<TokenStream> = Vec::new();
    let mut proto_name_arms = Vec::new();
    // Static slice for `Enumeration::values()`. Aliases are skipped — the
    // slice mirrors the *primary* declaration order, matching what
    // `from_i32` resolves to (so `MyEnum::values()[i].to_i32() ==
    // from_i32(...).unwrap().to_i32()` for unique values).
    let mut value_idents: Vec<Ident> = Vec::new();
    // The first primary variant becomes Default (see default_variant below).
    let mut first_variant: Option<Ident> = None;
    // Per-value records for idiomatic CamelCase alias generation, collected only
    // when the feature is enabled. Each entry is
    // `(proto_value_name, alias_target, own_ident_string)` where
    // `own_ident_string` is the value's existing variant/alias identifier (which
    // a CamelCase alias must not duplicate, and which keys `deprecated_idents`)
    // and `alias_target` is the variant a generated `const` would point at.
    let mut value_records: Vec<(String, Ident, String)> = Vec::new();
    let item_deprecated = deprecated_items(enum_desc);
    // Drives the `#[allow(deprecated)]` on the items that name variants. The
    // generated code names an alias const nowhere, so a deprecated alias of a
    // live variant needs no guard.
    let mut has_deprecated_variant = false;
    // Identifiers of the deprecated variants and alias consts, so the
    // idiomatic CamelCase const of each carries the marker too.
    let mut deprecated_idents: std::collections::HashSet<String> = std::collections::HashSet::new();

    for (v, &deprecated) in enum_desc.value.iter().zip(&item_deprecated) {
        let value_name = v
            .name
            .as_deref()
            .ok_or(CodeGenError::MissingField("enum_value.name"))?;
        let number = v
            .number
            .ok_or(CodeGenError::MissingField("enum_value.number"))?;
        let variant_ident = crate::message::make_field_ident(value_name);
        let value_fqn = format!("{}.{}", proto_fqn, value_name);
        let variant_doc =
            crate::comments::doc_attrs_resolved(ctx.comment(&value_fqn), proto_fqn, &ctx.type_map);
        // `#[deprecated]` from the value's `[deprecated = true]` option, as
        // prost-build emits it; see `deprecated_items` for the alias rule.
        let deprecated_attr = deprecated.then(|| quote! { #[deprecated] });
        if deprecated {
            deprecated_idents.insert(variant_ident.to_string());
        }

        if let Some(&primary_name) = seen.get(&number) {
            let primary_ident = crate::message::make_field_ident(primary_name);
            alias_consts.push(quote! {
                #variant_doc
                #deprecated_attr
                #[allow(non_upper_case_globals)]
                pub const #variant_ident: Self = Self::#primary_ident;
            });
            // Accept alias names in from_proto_name for JSON deserialization.
            from_proto_name_arms.push(quote! {
                #value_name => ::core::option::Option::Some(Self::#primary_ident)
            });
            if ctx.config.idiomatic_enum_aliases {
                value_records.push((
                    value_name.to_string(),
                    primary_ident,
                    variant_ident.to_string(),
                ));
            }
        } else {
            seen.insert(number, value_name);
            has_deprecated_variant |= deprecated;
            if first_variant.is_none() {
                first_variant = Some(variant_ident.clone());
            }
            variants.push(quote! { #variant_doc #deprecated_attr #variant_ident = #number });
            from_i32_arms.push(quote! {
                #number => ::core::option::Option::Some(Self::#variant_ident)
            });
            from_proto_name_arms.push(quote! {
                #value_name => ::core::option::Option::Some(Self::#variant_ident)
            });
            proto_name_arms.push(quote! {
                Self::#variant_ident => #value_name
            });
            if ctx.config.idiomatic_enum_aliases {
                value_records.push((
                    value_name.to_string(),
                    variant_ident.clone(),
                    variant_ident.to_string(),
                ));
            }
            value_idents.push(variant_ident);
        }
    }

    // Idiomatic CamelCase aliases (feature-gated; `value_records` is empty when
    // disabled). Returns the extra `const` items to emit and, when aliases are
    // suppressed by a conflict, a doc note to append to the enum.
    let enum_simple_name = enum_desc.name.as_deref().unwrap_or(rust_name);
    let (idiomatic_consts, idiomatic_doc_note) = idiomatic_aliases(
        ctx,
        rust_name,
        enum_simple_name,
        value_records,
        &deprecated_idents,
    );

    let deprecated_value_allow = has_deprecated_variant.then(|| quote! { #[allow(deprecated)] });
    let alias_block = if alias_consts.is_empty() && idiomatic_consts.is_empty() {
        quote! {}
    } else {
        quote! {
            #deprecated_value_allow
            impl #name_ident {
                #(#alias_consts)*
                #(#idiomatic_consts)*
            }
        }
    };

    // The default value of an enum type is its first declared value. For
    // open enums the spec additionally requires that first value to be 0, so
    // `first_variant` is correct for proto2, proto3, and editions alike —
    // and, unlike keying off closedness, it survives an enum-type override flipping
    // a proto2 enum's `enum_type` to OPEN (the declared default must not
    // change with the representation). Only a hand-built descriptor that
    // protoc would reject (open enum, non-zero first value) can observe a
    // difference, and there first-declared is the spec-faithful choice too.
    let default_variant = first_variant;
    let first_variant_deprecated = default_variant
        .as_ref()
        .is_some_and(|v| deprecated_idents.contains(&v.to_string()))
        .then(|| quote! { #[allow(deprecated)] });
    let default_block = match default_variant {
        Some(v) => quote! {
            // This impl names exactly one variant, so it needs the guard only
            // when that variant is the deprecated one.
            #first_variant_deprecated
            impl ::core::default::Default for #name_ident {
                fn default() -> Self {
                    Self::#v
                }
            }
        },
        None => quote! {},
    };

    let serde_impls = if ctx.config.generate_json {
        // `generate_enum_serde` returns multiple sibling items
        // (`impl Serialize`, `impl Deserialize`, `impl ProtoElemJson`). A
        // bare outer `#[cfg]` would attach only to the first; wrapping
        // them in a `#[cfg(...)] const _: () = { ... };` block lets one
        // outer cfg cover the lot — the anonymous const is itself a single
        // item, and trait impls inside it register globally on the enum
        // exactly as they would at module scope.
        crate::feature_gates::cfg_const_block(
            generate_enum_serde(&name_ident),
            ctx.config.feature_gates().json,
        )
    } else {
        quote! {}
    };
    // `derive(Arbitrary)` names every variant in code that carries the enum's
    // own spans, so it warns for a `#[deprecated]` variant and takes no lint
    // attribute to stop it. An enum with such a variant gets an impl that
    // indexes `Enumeration::values()` instead. It draws a `u32` and maps it to
    // a variant as the derive does (`derive_arbitrary` 1.4), so the choice of
    // impl does not change which message a fuzz input builds.
    let (arbitrary_derive, arbitrary_impl) =
        match (ctx.config.generate_arbitrary, has_deprecated_variant) {
            (false, _) => (quote! {}, quote! {}),
            (true, false) => (
                quote! { #[cfg_attr(feature = "arbitrary", derive(::arbitrary::Arbitrary))] },
                quote! {},
            ),
            (true, true) => (
                quote! {},
                quote! {
                    #[cfg(feature = "arbitrary")]
                    impl<'a> ::arbitrary::Arbitrary<'a> for #name_ident {
                        fn arbitrary(
                            u: &mut ::arbitrary::Unstructured<'a>,
                        ) -> ::arbitrary::Result<Self> {
                            let values = <Self as ::buffa::Enumeration>::values();
                            let draw = <u32 as ::arbitrary::Arbitrary>::arbitrary(u)?;
                            let index = (u64::from(draw) * values.len() as u64) >> 32;
                            ::core::result::Result::Ok(values[index as usize])
                        }

                        fn size_hint(depth: usize) -> (usize, ::core::option::Option<usize>) {
                            <u32 as ::arbitrary::Arbitrary>::size_hint(depth)
                        }
                    }
                },
            ),
        };

    // Vtable-mode reflection: closed enums appear as bare `#name_ident` in
    // `RepeatedView` / `MapView`, so they need a `ReflectElement` impl for the
    // generic container impls to apply. Open enums use `EnumValue<E>`, which
    // `buffa-descriptor` already covers, so the impl is emitted only for closed
    // enums — emitting it for open ones would just be dead `cargo doc` noise.
    let reflect_element_impl = if ctx.config.generate_reflection
        && ctx.config.generate_reflection_vtable
        && crate::message::is_closed_enum(&enum_features)
    {
        crate::feature_gates::cfg_block(
            quote! {
                impl ::buffa_descriptor::reflect::ReflectElement for #name_ident {
                    fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
                        ::buffa_descriptor::reflect::ValueRef::EnumNumber(
                            ::buffa::Enumeration::to_i32(self),
                        )
                    }
                }
            },
            ctx.config.feature_gates().reflect,
        )
    } else {
        quote! {}
    };

    let enum_doc = {
        let base =
            crate::comments::doc_attrs_resolved(ctx.comment(proto_fqn), proto_fqn, &ctx.type_map);
        quote! { #base #idiomatic_doc_note }
    };
    let custom_type_attrs = crate::context::CodeGenContext::matching_attributes(
        &ctx.config.type_attributes,
        proto_fqn,
    )?;
    let custom_enum_attrs = crate::context::CodeGenContext::matching_attributes(
        &ctx.config.enum_attributes,
        proto_fqn,
    )?;

    // A `skip_debug` rule naming the enum leaves `Debug` to the consuming
    // crate.
    let derives = if ctx.skip_debug_enum(proto_fqn) {
        quote! { #[derive(Clone, Copy, PartialEq, Eq, Hash)] }
    } else {
        quote! { #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] }
    };

    // Proto enum values are SCREAMING_CASE variants. The module-tree wrapper
    // already allows this lint (`ALLOW_LINTS`), but a content file consumed
    // on its own (`include!` or `mod` without the wrapper) is not covered, so
    // the enum carries it too, like the scoped `non_snake_case` allow on
    // messages (#408). A regular `//` comment inside `quote!` is dropped,
    // which is why this note sits outside it.
    let zeroize_impl = if ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty() {
        quote! { impl ::buffa::sensitive::Zeroize for #name_ident {
            fn zeroize(&mut self) { ::buffa::sensitive::reset_copy(self); }
        } }
    } else {
        quote! {}
    };
    let inspect_impl = if ctx.config.generate_reflection
        && (ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty())
        && crate::message::is_closed_enum(&enum_features)
    {
        crate::feature_gates::cfg_block(
            quote! {
                impl ::buffa_descriptor::reflect::InspectElement for #name_ident {
                    fn as_inspect_value(&self) -> ::buffa_descriptor::reflect::InspectValueRef<'_> {
                        ::buffa_descriptor::reflect::InspectValueRef::EnumNumber(
                            ::buffa::Enumeration::to_i32(self),
                        )
                    }
                }
            },
            ctx.config.feature_gates().reflect,
        )
    } else {
        quote! {}
    };
    Ok(quote! {
        #enum_doc
        #[allow(non_camel_case_types)]
        #derives
        #arbitrary_derive
        #custom_type_attrs
        #custom_enum_attrs
        #[repr(i32)]
        pub enum #name_ident {
            #(#variants,)*
        }

        #alias_block

        #default_block
        #zeroize_impl
        #inspect_impl

        #serde_impls

        #deprecated_value_allow
        impl ::buffa::Enumeration for #name_ident {
            fn from_i32(value: i32) -> ::core::option::Option<Self> {
                match value {
                    #(#from_i32_arms,)*
                    _ => ::core::option::Option::None,
                }
            }

            fn to_i32(&self) -> i32 {
                *self as i32
            }

            fn proto_name(&self) -> &'static str {
                match self {
                    #(#proto_name_arms,)*
                }
            }

            fn from_proto_name(name: &str) -> ::core::option::Option<Self> {
                match name {
                    #(#from_proto_name_arms,)*
                    _ => ::core::option::Option::None,
                }
            }

            fn values() -> &'static [Self] {
                &[#(Self::#value_idents),*]
            }
        }

        #reflect_element_impl

        #arbitrary_impl
    })
}

/// Compute idiomatic `UpperCamelCase` alias `const`s for an enum.
///
/// `records` holds one entry per proto value (empty when the feature is
/// disabled): `(proto_value_name, alias_target, own_ident_string)`, where
/// `own_ident_string` is the value's existing variant/alias identifier (which a
/// CamelCase alias must not duplicate). The proto names stay the definitive
/// variants; this only adds aliases. A const is `#[deprecated]` when
/// `deprecated_idents` holds the `own_ident_string` of the value it comes from.
///
/// Returns the `const` items to emit and a doc-note token stream (empty unless
/// aliases were suppressed). The rule is all-or-nothing per enum: if any two
/// values would collide after conversion — or a value would yield an invalid
/// identifier — no aliases are emitted, a [`CodeGenWarning`](crate::CodeGenWarning)
/// is recorded on `ctx`, and the returned doc note explains the suppression. This
/// guarantees a match is never forced to mix `SHOUTY_SNAKE_CASE` and idiomatic
/// names.
fn idiomatic_aliases(
    ctx: &CodeGenContext,
    rust_name: &str,
    enum_simple_name: &str,
    records: Vec<(String, Ident, String)>,
    deprecated_idents: &std::collections::HashSet<String>,
) -> (Vec<TokenStream>, TokenStream) {
    use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
    use std::fmt::Write;

    if records.is_empty() {
        return (Vec::new(), quote! {});
    }

    let is_valid = |c: &str| !c.is_empty() && !c.starts_with(|ch: char| ch.is_ascii_digit());

    let prefix = format!("{}_", crate::idents::to_shouty_snake_case(enum_simple_name));

    // Strip the enum-name prefix only if *every* value carries it and stays a
    // valid identifier afterwards; otherwise keep full names. Deciding this for
    // the whole enum (not per value) keeps the result from mixing stripped and
    // unstripped names.
    let strip = records.iter().all(|(name, ..)| {
        name.strip_prefix(&prefix)
            .is_some_and(|base| is_valid(&crate::idents::to_upper_camel_case(base)))
    });

    let camel = |name: &str| {
        let base = if strip {
            name.strip_prefix(&prefix).unwrap_or(name)
        } else {
            name
        };
        crate::idents::to_upper_camel_case(base)
    };

    // Identifiers already occupying the enum's type namespace (variants + proto
    // `allow_alias` consts), guaranteed unique by protobuf, owned so `records`
    // can be consumed below.
    let existing: HashSet<String> = records.iter().map(|(_, _, own)| own.clone()).collect();

    // Group proto values by the escaped CamelCase identifier they would claim.
    // A value also pulls in the owner of an existing variant/alias its CamelCase
    // form lands on — that is the silent variant↔const shadow case.
    let mut buckets: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut invalid: BTreeSet<String> = BTreeSet::new();
    {
        let owner: HashMap<&str, &str> = records
            .iter()
            .map(|(name, _, own)| (own.as_str(), name.as_str()))
            .collect();
        for (name, _, _) in &records {
            let candidate = camel(name);
            if !is_valid(&candidate) {
                // Defensive: unreachable under the current strip logic (the
                // stripped path is taken only when every value stays valid, and
                // the unstripped path uses raw proto names, which are never empty
                // or digit-leading). Kept so a future converter that can emit an
                // invalid identifier still suppresses rather than emits bad code.
                invalid.insert(name.clone());
                continue;
            }
            let escaped = crate::idents::make_field_ident(&candidate).to_string();
            if let Some(&existing_owner) = owner.get(escaped.as_str()) {
                buckets
                    .entry(escaped.clone())
                    .or_default()
                    .insert(existing_owner.to_string());
            }
            buckets.entry(escaped).or_default().insert(name.clone());
        }
    }

    let conflicts: Vec<(&String, &BTreeSet<String>)> = buckets
        .iter()
        .filter(|(_, claimants)| claimants.len() > 1)
        .collect();

    if conflicts.is_empty() && invalid.is_empty() {
        // Clean: emit an alias for every value whose CamelCase form differs from
        // its own variant/alias identifier (skipping the redundant ones, which
        // are the only way an emitted name can already be in `existing`).
        let consts = records
            .into_iter()
            .filter_map(|(name, target, own)| {
                let escaped = crate::idents::make_field_ident(&camel(&name));
                if existing.contains(&escaped.to_string()) {
                    return None;
                }
                // A short doc instead of duplicating the variant's proto comment:
                // links the reader to the canonical variant and warns that
                // `Debug` prints the variant name, not this alias. Raw
                // identifiers (e.g. `r#type`) don't resolve as intra-doc
                // links, so fall back to plain code formatting for those.
                let target_name = target.to_string();
                // The CamelCase const is another name for the value it is
                // derived from, so it carries that value's marker.
                let deprecated_attr = deprecated_idents
                    .contains(&own)
                    .then(|| quote! { #[deprecated] });
                let alias_doc = if let Some(stripped) = target_name.strip_prefix("r#") {
                    format!("Idiomatic alias for `{stripped}`; `Debug` prints the variant name.")
                } else {
                    format!(
                        "Idiomatic alias for [`Self::{target_name}`]; `Debug` prints the variant name."
                    )
                };
                Some(quote! {
                    #[doc = #alias_doc]
                    #deprecated_attr
                    #[allow(non_upper_case_globals)]
                    pub const #escaped: Self = Self::#target;
                })
            })
            .collect();
        return (consts, quote! {});
    }

    // Suppressed: record a structured warning and an enum doc note describing
    // every clash, so the reason is visible both at build time and in docs.
    let conflict_data: Vec<crate::AliasConflict> = conflicts
        .iter()
        .map(|(camel_ident, claimants)| crate::AliasConflict {
            camel_target: (*camel_ident).clone(),
            proto_values: claimants.iter().cloned().collect(),
        })
        .collect();
    let invalid_data: Vec<String> = invalid.into_iter().collect();

    // Build the doc note by borrowing, then hand both lists to `warn` by move.
    let mut note = String::from(
        "Idiomatic CamelCase aliases are not generated for this enum: two or more proto values \
         collide after conversion (or would be invalid identifiers). Use the `SHOUTY_SNAKE_CASE` \
         variants directly. Collisions:\n",
    );
    for conflict in &conflict_data {
        let joined = conflict
            .proto_values
            .iter()
            .map(|n| format!("`{n}`"))
            .collect::<Vec<_>>()
            .join(", ");
        let _ = writeln!(note, "- {joined} → `{}`", conflict.camel_target);
    }
    for name in &invalid_data {
        let _ = writeln!(note, "- `{name}` produces an invalid identifier");
    }

    ctx.warn(crate::CodeGenWarning::IdiomaticAliasesSuppressed {
        enum_name: rust_name.to_string(),
        conflicts: conflict_data,
        invalid: invalid_data,
    });

    (Vec::new(), quote! { #[doc = #note] })
}