Skip to main content

buffa_codegen/
lib.rs

1// Modified by ReallyMe Technologies Limited.
2//! Shared code generation logic for buffa.
3//!
4//! This crate takes protobuf descriptors (`google.protobuf.FileDescriptorProto`,
5//! decoded from binary `FileDescriptorSet` data) and emits Rust source code
6//! that uses the `buffa` runtime.
7//!
8//! It is used by:
9//! - `protoc-gen-reallyme-buffa` (protoc plugin)
10//! - `buffa-build` (build.rs integration)
11//!
12//! # Architecture
13//!
14//! The code generator is intentionally decoupled from how descriptors are
15//! obtained. It receives fully-resolved `FileDescriptorProto`s and produces
16//! Rust source strings. This means:
17//!
18//! - It doesn't parse `.proto` files.
19//! - It doesn't invoke `protoc`.
20//! - It doesn't do import resolution or name linking.
21//!
22//! All of that is handled upstream (by protoc, buf, or a future parser).
23
24pub(crate) mod comments;
25pub mod context;
26pub(crate) mod defaults;
27pub(crate) mod enumeration;
28pub(crate) mod extension;
29pub(crate) mod feature_gates;
30pub use feature_gates::FeatureGateNames;
31pub(crate) mod features;
32pub(crate) mod field_names;
33#[doc(hidden)]
34pub use buffa_descriptor::generated;
35pub(crate) mod feature_overrides;
36pub mod idents;
37pub(crate) mod impl_message;
38pub(crate) mod impl_text;
39pub(crate) mod imports;
40pub(crate) mod json_policy;
41pub(crate) mod lazy_view;
42pub(crate) mod message;
43pub(crate) mod oneof;
44pub(crate) mod owned_view;
45pub(crate) mod reflect;
46pub(crate) mod reflect_owned;
47pub(crate) mod reflect_view;
48pub(crate) mod table_codec;
49pub(crate) mod table_plan;
50pub(crate) mod view;
51
52use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
53use proc_macro2::TokenStream;
54use quote::{format_ident, quote};
55
56const GENERATED_HEADER: &str = concat!(
57    "// @generated by reallyme-buffa-codegen ",
58    env!("CARGO_PKG_VERSION"),
59    ". DO NOT EDIT.\n",
60    "// Modified by ReallyMe Technologies Limited.\n",
61);
62
63/// Environment variable overriding the element-memory bound buffa's tooling
64/// applies when decoding a descriptor set.
65///
66/// Accepts a byte count, or `unlimited` / `max` (both lowercase) for no bound.
67/// A value that is not valid UTF-8 is treated as unset.
68pub const ELEMENT_MEMORY_LIMIT_ENV: &str = "BUFFA_ELEMENT_MEMORY_LIMIT";
69
70/// Element-memory bound buffa's build tooling applies to a descriptor set —
71/// the `protoc` plugins to a `CodeGeneratorRequest`, `buffa-build` to a
72/// `FileDescriptorSet`.
73///
74/// Much higher than [`buffa::DEFAULT_ELEMENT_MEMORY_LIMIT`], which is sized for
75/// untrusted input: a build's descriptors come from a compiler the caller
76/// invoked, or a file the caller named. It is deliberately not unbounded, so a
77/// truncated or corrupt descriptor set still fails with an error rather than
78/// exhausting memory.
79///
80/// 1 GiB is roughly twice what the largest schemas need. Descriptor types are
81/// wide structs, so the element footprint runs several times the encoded size
82/// — around 6x in practice, making this about 160 MB of descriptors.
83pub const TOOLING_ELEMENT_MEMORY_LIMIT: usize = 1024 * 1024 * 1024;
84
85/// Decode options for a descriptor set produced by the caller's own build,
86/// honouring [`ELEMENT_MEMORY_LIMIT_ENV`].
87///
88/// The override is an environment variable rather than a `protoc` plugin
89/// option because the options string travels *inside* the request: it cannot
90/// be read until the request has already been decoded.
91///
92/// # Errors
93///
94/// Returns a message naming the variable if its value is not a byte count or
95/// `unlimited` / `max`.
96pub fn tooling_decode_options() -> Result<buffa::DecodeOptions, String> {
97    let raw = std::env::var(ELEMENT_MEMORY_LIMIT_ENV).ok();
98    let limit = parse_element_memory_limit(raw.as_deref())?;
99    Ok(buffa::DecodeOptions::new().with_element_memory_limit(limit))
100}
101
102/// Describe a failure to decode a descriptor set, naming the override when the
103/// element-memory bound is what rejected it.
104///
105/// `subject` is the message being decoded, e.g. `"CodeGeneratorRequest"`.
106/// `limit` is the bound that was actually in force, which is not
107/// [`TOOLING_ELEMENT_MEMORY_LIMIT`] once the environment overrides it — read it
108/// back with `DecodeOptions::element_memory_limit`.
109///
110/// The bare error text names no remedy, and whoever hits the bound is exactly
111/// who needs [`ELEMENT_MEMORY_LIMIT_ENV`] — so the hint belongs on the message
112/// they see, not only in the guide.
113#[must_use]
114pub fn decode_failure(subject: &str, err: &buffa::DecodeError, limit: usize) -> String {
115    let base = format!("failed to decode {subject}: {err}");
116    match err {
117        buffa::DecodeError::ElementMemoryLimitExceeded => format!(
118            "{base}\n\
119             These descriptors exceed the {budget} element-memory budget in force. \
120             Raise it with the {opt}=<bytes> plugin option or the {env} environment \
121             variable; either accepts 'unlimited'. See \"Very large schemas\" in the \
122             buffa guide.",
123            budget = describe_byte_budget(limit),
124            opt = ELEMENT_MEMORY_LIMIT_OPT,
125            env = ELEMENT_MEMORY_LIMIT_ENV,
126        ),
127        _ => base,
128    }
129}
130
131/// Render a byte budget for a human: MiB once that is a whole number, bytes
132/// below that. A sub-MiB limit is legitimate (the environment variable takes a
133/// raw byte count), and truncating it to "0 MiB" would make the hint absurd.
134fn describe_byte_budget(bytes: usize) -> String {
135    const MIB: usize = 1024 * 1024;
136    if bytes >= MIB && bytes % MIB == 0 {
137        format!("{} MiB", bytes / MIB)
138    } else {
139        format!("{bytes}-byte")
140    }
141}
142
143/// Plugin option, settable in the `protoc`/`buf` parameter string, that sets
144/// the element-memory bound used to decode the request carrying it.
145pub const ELEMENT_MEMORY_LIMIT_OPT: &str = "element_memory_limit";
146
147/// Read `CodeGeneratorRequest.parameter` (field 2) straight off the wire,
148/// without decoding the request.
149///
150/// An option that governs how the request itself is decoded cannot be read
151/// from the decoded request. Scanning for the one field is what makes such
152/// options possible: it skips every other field rather than materialising it,
153/// so the cost is a wire walk, not a decode — microseconds against the tens of
154/// milliseconds a full decode of a large request takes.
155///
156/// Returns `None` when the request carries no parameter.
157///
158/// # Errors
159///
160/// Returns a [`DecodeError`](buffa::DecodeError) if the bytes are not
161/// well-formed protobuf, or if the parameter is not valid UTF-8.
162pub fn peek_request_parameter(mut buf: &[u8]) -> Result<Option<&str>, buffa::DecodeError> {
163    use buffa::encoding::{decode_varint, skip_field, Tag, WireType};
164
165    /// `CodeGeneratorRequest.parameter`.
166    const PARAMETER_FIELD: u32 = 2;
167
168    let mut found = None;
169    while !buf.is_empty() {
170        let tag = Tag::decode(&mut buf)?;
171        if tag.field_number() == PARAMETER_FIELD && tag.wire_type() == WireType::LengthDelimited {
172            let len = usize::try_from(decode_varint(&mut buf)?)
173                .map_err(|_| buffa::DecodeError::MessageTooLarge)?;
174            if len > buf.len() {
175                return Err(buffa::DecodeError::UnexpectedEof);
176            }
177            let (value, rest) = buf.split_at(len);
178            // Last wins, matching how protobuf merges a repeated scalar field.
179            found = Some(core::str::from_utf8(value).map_err(|_| buffa::DecodeError::InvalidUtf8)?);
180            buf = rest;
181            continue;
182        }
183        skip_field(tag, &mut buf)?;
184    }
185    Ok(found)
186}
187
188/// Find `element_memory_limit=<value>` in a `protoc` plugin parameter string.
189///
190/// Returns `None` when the option is absent, leaving
191/// [`ELEMENT_MEMORY_LIMIT_ENV`] and then [`TOOLING_ELEMENT_MEMORY_LIMIT`] to
192/// supply the value.
193///
194/// # Errors
195///
196/// Returns a message if the option is present with an unparseable value.
197pub fn element_memory_limit_opt(parameter: &str) -> Result<Option<usize>, String> {
198    let mut found = None;
199    for entry in parameter.split(',').map(str::trim) {
200        if let Some((key, value)) = entry.split_once('=') {
201            if key.trim() == ELEMENT_MEMORY_LIMIT_OPT {
202                found = Some(parse_element_memory_limit(Some(value))?);
203            }
204        }
205    }
206    Ok(found)
207}
208
209/// Decode a `CodeGeneratorRequest` from a `protoc` plugin's stdin.
210///
211/// The element-memory bound is taken from the `element_memory_limit` plugin
212/// option if the request carries one, else [`ELEMENT_MEMORY_LIMIT_ENV`], else
213/// [`TOOLING_ELEMENT_MEMORY_LIMIT`]. The option is read by scanning for it
214/// ([`peek_request_parameter`]) rather than from the decoded request, since it
215/// governs that decode.
216///
217/// Both plugins compose exactly this, so it lives here: a hint improved in one
218/// binary should never disagree with the other.
219///
220/// # Errors
221///
222/// Returns a message describing the failure, naming the ways to raise the
223/// bound when that is what rejected the request.
224pub fn decode_request(input: &[u8]) -> Result<generated::compiler::CodeGeneratorRequest, String> {
225    let parameter = peek_request_parameter(input)
226        .map_err(|e| format!("failed to read the plugin parameter: {e}"))?
227        .unwrap_or_default();
228    let options = match element_memory_limit_opt(parameter)? {
229        Some(limit) => buffa::DecodeOptions::new().with_element_memory_limit(limit),
230        None => tooling_decode_options()?,
231    };
232    options
233        .decode_from_slice::<generated::compiler::CodeGeneratorRequest>(input)
234        .map_err(|e| decode_failure("CodeGeneratorRequest", &e, options.element_memory_limit()))
235}
236
237/// Resolve [`ELEMENT_MEMORY_LIMIT_ENV`]'s value to a byte count.
238///
239/// `None` and an all-whitespace value both mean "unset", yielding
240/// [`TOOLING_ELEMENT_MEMORY_LIMIT`].
241///
242/// # Errors
243///
244/// Returns a message naming the variable if the value is neither a byte count
245/// nor `unlimited` / `max`.
246pub(crate) fn parse_element_memory_limit(raw: Option<&str>) -> Result<usize, String> {
247    let Some(raw) = raw else {
248        return Ok(TOOLING_ELEMENT_MEMORY_LIMIT);
249    };
250    match raw.trim() {
251        "" => Ok(TOOLING_ELEMENT_MEMORY_LIMIT),
252        "unlimited" | "max" => Ok(usize::MAX),
253        n => n.parse::<usize>().map_err(|_| {
254            format!("{ELEMENT_MEMORY_LIMIT_ENV}: expected a byte count or 'unlimited', got '{raw}'")
255        }),
256    }
257}
258
259/// Lints suppressed on generated code at module boundaries.
260///
261/// Consumed by [`generate_module_tree`], the per-package `.mod.rs`
262/// stitcher, and `buffa-build`'s `_include.rs` writer. One list keeps
263/// them in sync.
264pub const ALLOW_LINTS: &[&str] = &[
265    "non_camel_case_types",
266    "dead_code",
267    "unused_imports",
268    // Cross-proto refs within the same package are emitted through the
269    // canonical `super::super::__buffa::view::…` path even though the
270    // target lives in the same generated module — using the bare name
271    // would resolve, but the canonical path is stable when a sibling
272    // proto defines a same-named natural-path re-export.
273    "unused_qualifications",
274    "clippy::derivable_impls",
275    "clippy::match_single_binding",
276    "clippy::uninlined_format_args",
277    "clippy::doc_lazy_continuation",
278    // A user `message View { message Inner }` produces
279    // `__buffa::view::view::InnerView`; harmless but trips this lint.
280    "clippy::module_inception",
281];
282
283/// Render [`ALLOW_LINTS`] as a `#[allow(…)]` attribute token stream.
284pub fn allow_lints_attr() -> TokenStream {
285    let lints: Vec<TokenStream> = ALLOW_LINTS
286        .iter()
287        .map(|l| syn::parse_str(l).expect("lint name parses as path"))
288        .collect();
289    quote! { #[allow( #(#lints),* )] }
290}
291
292/// One generated output file.
293///
294/// Each `.proto` produces up to five **content files** (`<stem>.rs`,
295/// `<stem>.__view.rs`, `<stem>.__oneof.rs`, `<stem>.__view_oneof.rs`,
296/// `<stem>.__ext.rs`) and each proto package produces one
297/// `<dotted.pkg>.mod.rs` **stitcher** that `include!`s the content files
298/// and authors the `pub mod __buffa { … }` ancillary tree.
299/// Ancillary kinds with no content for that input file (e.g. a message
300/// with no oneofs and no extensions) are omitted, and the stitcher's
301/// `include!` set is filtered to match. The `__buffa` wrapper (and each
302/// `view` / `oneof` / `ext` submodule inside it) is itself omitted when
303/// it would be empty, so packages with only owned messages emit no
304/// `__buffa` block at all.
305/// See `DESIGN.md` → "Generated code layout".
306///
307/// Consumers normally only need to wire up the
308/// [`GeneratedFileKind::PackageMod`] entries (one per package); the
309/// per-proto content kinds are reached transitively via `include!` from
310/// the stitcher. Write all files to disk; build a module tree from only
311/// the `PackageMod` ones.
312///
313/// With [`CodeGenConfig::file_per_package`] set, the per-proto content
314/// kinds are not emitted at all — the single `<dotted.pkg>.rs` (still
315/// kind `PackageMod`) inlines what the stitcher would `include!`.
316#[derive(Debug)]
317pub struct GeneratedFile {
318    /// The output file path (e.g., `"my.pkg.foo.rs"` or `"my.pkg.mod.rs"`).
319    pub name: String,
320    /// The proto package this file belongs to.
321    pub package: String,
322    /// What this file contains. Build integrations only need to wire up
323    /// [`GeneratedFileKind::PackageMod`] files; everything else is reached
324    /// via `include!` from there.
325    pub kind: GeneratedFileKind,
326    /// The generated Rust source code.
327    pub content: String,
328}
329
330/// Kind of [`GeneratedFile`].
331///
332/// [`generate`] produces up to five per-proto content kinds — one each
333/// of [`Owned`](Self::Owned), [`View`](Self::View), [`Oneof`](Self::Oneof),
334/// [`ViewOneof`](Self::ViewOneof), and [`Ext`](Self::Ext) per input
335/// `.proto` file — plus one [`PackageMod`](Self::PackageMod) stitcher per
336/// package. Kinds with no content for the input (a proto with no oneofs
337/// emits no [`Oneof`](Self::Oneof) / [`ViewOneof`](Self::ViewOneof);
338/// no extensions, no [`Ext`](Self::Ext); etc.) are omitted. Build
339/// integrations only need to wire up `PackageMod` entries; the per-proto
340/// content kinds are reached via `include!` from the stitcher and need
341/// only be written to disk alongside it. Under
342/// [`CodeGenConfig::file_per_package`] only `PackageMod` is emitted.
343///
344/// [`Companion`](Self::Companion) is the one kind *not* produced by
345/// [`generate`]: downstream code generators construct `Companion` files
346/// themselves and merge them into buffa's output via
347/// [`apply_companions`].
348///
349/// This enum is `#[non_exhaustive]` — match with a wildcard arm so new
350/// kinds can be added without a major version bump.
351#[derive(Debug, Clone, Copy, PartialEq, Eq)]
352#[non_exhaustive]
353pub enum GeneratedFileKind {
354    /// Owned message structs and enums (`<stem>.rs`).
355    Owned,
356    /// View structs (`<stem>.__view.rs`).
357    View,
358    /// Lazy view structs (`<stem>.__lazy_view.rs`).
359    LazyView,
360    /// Owned oneof enums (`<stem>.__oneof.rs`).
361    Oneof,
362    /// View oneof enums (`<stem>.__view_oneof.rs`).
363    ViewOneof,
364    /// File-level proto-extension consts (`<stem>.__ext.rs`) — the
365    /// `pub const` `ExtensionDescriptor` items generated from `extend`
366    /// blocks. Not to be confused with [`Companion`](Self::Companion),
367    /// which is unrelated downstream-supplied content.
368    Ext,
369    /// Per-package stitcher (`<dotted.pkg>.mod.rs`). The only file build
370    /// systems need to wire up directly.
371    PackageMod,
372    /// Extra per-proto content from a downstream code generator (service
373    /// stubs, extra trait impls, etc.) that travels with buffa's output.
374    ///
375    /// Not produced by [`generate`]. Construct these in your own generator
376    /// and pass them to [`apply_companions`], which appends an `include!`
377    /// for each one at file scope in the matching package's
378    /// [`PackageMod`](Self::PackageMod) — after buffa's own output, at
379    /// package root alongside the owned message types (**not** under the
380    /// `__buffa::` sentinel module). Items declared `pub` in a companion
381    /// file are visible at `crate::<pkg>::*`.
382    ///
383    /// Not to be confused with [`Ext`](Self::Ext), which is the buffa-
384    /// generated file holding protobuf `extend` consts.
385    Companion,
386}
387
388/// Parse a custom owned-type path string (e.g. `"::smol_str::SmolStr"`) into a
389/// token stream, validating it as a Rust type so a malformed path surfaces as a
390/// codegen error rather than unparseable generated output.
391pub(crate) fn parse_custom_type_path(path: &str) -> Result<proc_macro2::TokenStream, CodeGenError> {
392    let ty: syn::Type =
393        syn::parse_str(path).map_err(|_| CodeGenError::InvalidTypePath(path.to_string()))?;
394    Ok(quote::quote! { #ty })
395}
396
397/// Parse a custom **map** container path, which is applied as `path<K, V>`.
398///
399/// The path must therefore be a bare type path with no `<...>` parameters of its
400/// own (and, unlike the box/repeated knobs, no `*` placeholder — a map's key and
401/// value are appended positionally). Reject anything else with a message that
402/// names the convention, rather than letting `Foo<Bar><K, V>` surface as an
403/// opaque whole-file parse error later.
404pub(crate) fn parse_custom_map_path(path: &str) -> Result<proc_macro2::TokenStream, CodeGenError> {
405    let ty: syn::Type = syn::parse_str(path).map_err(|_| {
406        CodeGenError::InvalidTypePath(format!(
407            "{path} (map custom path takes no `<K, V>` parameters and no `*` placeholder)"
408        ))
409    })?;
410    let syn::Type::Path(tp) = &ty else {
411        return Err(CodeGenError::InvalidTypePath(format!(
412            "{path} (map custom path must be a plain type path)"
413        )));
414    };
415    if tp
416        .path
417        .segments
418        .iter()
419        .any(|s| !matches!(s.arguments, syn::PathArguments::None))
420    {
421        return Err(CodeGenError::InvalidTypePath(format!(
422            "{path} (map custom path must not include `<K, V>`; the key and value are appended automatically)"
423        )));
424    }
425    Ok(quote::quote! { #ty })
426}
427
428/// Build a custom wrapper type from a `*`-templated path and a resolved inner
429/// type, validating the result as a Rust type.
430///
431/// `*` cannot be a parsed placeholder (it is not valid in Rust type position),
432/// so substitution is textual — every `*` in `template` is replaced by `inner`'s
433/// token text before the whole string is parsed. Used by the pluggable pointer
434/// knob, where the wrapped type sits inside extra generic parameters (e.g.
435/// `"smallbox::SmallBox<*, S4>"`). The template must contain at least one `*`.
436pub(crate) fn parse_wildcard_type_path(
437    template: &str,
438    inner: &proc_macro2::TokenStream,
439) -> Result<proc_macro2::TokenStream, CodeGenError> {
440    if !template.contains('*') {
441        return Err(CodeGenError::MissingWildcard(template.to_string()));
442    }
443    let substituted = template.replace('*', &inner.to_string());
444    let ty: syn::Type = syn::parse_str(&substituted)
445        .map_err(|_| CodeGenError::InvalidTypePath(format!("{template} (as {substituted})")))?;
446    Ok(quote::quote! { #ty })
447}
448
449/// Build a custom collection type from a `*`-templated path and the resolved
450/// element type, validating the result as a Rust type.
451///
452/// `*` cannot be a parsed placeholder (it is not valid in Rust type position),
453/// so substitution is textual — every `*` in `template` is replaced by the
454/// element's token text before the whole string is parsed. The template must
455/// contain at least one `*`, otherwise the element type would have nowhere to
456/// go and the field would silently drop its element type.
457pub(crate) fn parse_custom_list_path(
458    template: &str,
459    elem: &proc_macro2::TokenStream,
460) -> Result<proc_macro2::TokenStream, CodeGenError> {
461    if !template.contains('*') {
462        return Err(CodeGenError::MissingListPlaceholder(template.to_string()));
463    }
464    let substituted = template.replace('*', &elem.to_string());
465    let ty: syn::Type = syn::parse_str(&substituted)
466        .map_err(|_| CodeGenError::InvalidTypePath(template.to_string()))?;
467    Ok(quote::quote! { #ty })
468}
469
470/// The Rust type a proto `string` field maps to in generated owned structs.
471///
472/// The default is [`String`](StringRepr::String).
473/// [`Custom`](StringRepr::Custom) substitutes any type named by its
474/// fully-qualified Rust path — for example `::smol_str::SmolStr`,
475/// `::ecow::EcoString`, or `::compact_str::CompactString` for read-mostly
476/// schemas — that satisfies the `buffa::ProtoString` bound. The downstream crate
477/// must itself depend on the crate providing that type (buffa does not re-export
478/// it).
479///
480/// Select a representation through `buffa_build`'s `string_type` /
481/// `string_type_custom` builder methods. The wire format is identical regardless
482/// of representation — only the in-memory owned type changes, and view types
483/// keep borrowing `&str`. A rule that matches a `map` field applies to its
484/// `string` key and its `string` value.
485#[derive(Debug, Clone, PartialEq, Eq, Default)]
486#[non_exhaustive]
487pub enum StringRepr {
488    /// `::buffa::alloc::string::String` — growable and mutable (the default).
489    #[default]
490    String,
491    /// A custom type named by its fully-qualified Rust path (e.g.
492    /// `"::smol_str::SmolStr"`). Must satisfy `buffa::ProtoString` and be
493    /// provided by a crate the downstream depends on.
494    ///
495    /// # Limitations
496    ///
497    /// - With `generate_reflection_vtable`, a *foreign* custom type used as a
498    ///   `repeated` element or as a `map` key or value fails to compile (the
499    ///   emitted `ReflectElement` / `ReflectMapKey` impl violates the orphan
500    ///   rule). Wrap it in a crate-local newtype, or set
501    ///   [`CodeGenConfig::emit_custom_type_impls`] to `false` when the defining
502    ///   crate supplies those integrations. Singular / optional / oneof uses
503    ///   work with a foreign type directly.
504    /// - A custom type used as a `map` key must implement `Hash + Eq` for
505    ///   [`MapRepr::HashMap`], or `Ord` for [`MapRepr::BTreeMap`].
506    /// - With `generate_json`, a custom type on an `optional`, `repeated` or
507    ///   oneof field, or used as a `map` key or value, must implement
508    ///   `serde::Serialize` and `serde::Deserialize`. A singular field without
509    ///   `optional` needs no `serde` impl.
510    /// - A path that does not parse as a Rust type surfaces as
511    ///   [`CodeGenError::InvalidTypePath`] at generation (`.compile()`) time.
512    /// - The per-element impls are deduplicated within a single generation, but
513    ///   the *same* crate-local type used as a `repeated` element across two
514    ///   separate `compile()` invocations in one crate emits the impl twice (a
515    ///   duplicate-impl `E0119`). Generate from a single `compile()`, use
516    ///   distinct element types, or disable generated integrations and provide
517    ///   them once in the defining crate.
518    Custom(String),
519}
520
521impl StringRepr {
522    /// The owned Rust type path emitted for a `string` field with this
523    /// representation.
524    ///
525    /// `ctx` and `nesting` route the default `String` through the package-root
526    /// import registry (`idiomatic_imports`); a custom path is parsed and
527    /// emitted fully qualified.
528    ///
529    /// # Errors
530    ///
531    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
532    /// as a Rust type.
533    pub(crate) fn type_path(
534        &self,
535        resolver: &imports::ImportResolver,
536        ctx: &context::CodeGenContext,
537        nesting: usize,
538    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
539        match self {
540            StringRepr::String => Ok(resolver.string_at(ctx, nesting)),
541            StringRepr::Custom(path) => parse_custom_type_path(path),
542        }
543    }
544
545    /// Whether this is the default `String` representation, which keeps the
546    /// `String`-specialized fast paths (in-place `merge_string`, `clear()`,
547    /// native `Arbitrary`) instead of the generic `ProtoString` ones.
548    pub(crate) fn is_default(&self) -> bool {
549        matches!(self, StringRepr::String)
550    }
551}
552
553/// The Rust type a proto `bytes` field maps to in generated owned structs.
554///
555/// The default is [`Vec`](BytesRepr::Vec) (`Vec<u8>`). [`Bytes`](BytesRepr::Bytes)
556/// uses `bytes::Bytes`, which decodes zero-copy from a
557/// `Bytes`-backed buffer. [`Custom`](BytesRepr::Custom) substitutes any type
558/// named by its fully-qualified Rust path that satisfies the `buffa::ProtoBytes`
559/// bound; the downstream crate must itself depend on the providing crate.
560///
561/// Select a representation through `buffa_build`'s `bytes_type` /
562/// `bytes_type_custom` builder methods (or the legacy `use_bytes_type`, which
563/// selects [`Bytes`](BytesRepr::Bytes)). The wire format is identical regardless
564/// of representation, and view types keep borrowing `&[u8]`. A rule that
565/// matches a `map` field applies to its `bytes` value. One map shape keeps
566/// `Vec<u8>` values whatever rule matches: a map whose `string` key is mapped
567/// to `bytes` by [`strict_utf8_mapping`](CodeGenConfig::strict_utf8_mapping)
568/// (`utf8_validation = NONE` on the key) and whose value is `bytes`.
569#[derive(Debug, Clone, PartialEq, Eq, Default)]
570#[non_exhaustive]
571pub enum BytesRepr {
572    /// `::buffa::alloc::vec::Vec<u8>` — growable and mutable (the default).
573    #[default]
574    Vec,
575    /// `::buffa::bytes::Bytes` — reference-counted, immutable, decodes zero-copy
576    /// from a `Bytes`-backed buffer.
577    Bytes,
578    /// A custom type named by its fully-qualified Rust path. Must satisfy
579    /// `buffa::ProtoBytes` and be provided by a crate the downstream depends on.
580    ///
581    /// # Limitations
582    ///
583    /// - A *foreign* custom type used as a `repeated` element fails to compile
584    ///   (the emitted `ReflectElement` / `ProtoElemJson` impls violate the
585    ///   orphan rule). Wrap it in a crate-local newtype, or set
586    ///   [`CodeGenConfig::emit_custom_type_impls`] to `false` when the defining
587    ///   crate supplies those integrations. Singular / optional / oneof uses
588    ///   work with a foreign type directly.
589    /// - A `Custom` rule applies to `map<K, bytes>` values, as
590    ///   [`Bytes`](BytesRepr::Bytes) does. With `generate_json` or
591    ///   `generate_reflection_vtable`, codegen emits `ProtoElemJson` /
592    ///   `ReflectElement` impls for the value type, so it must be a
593    ///   crate-local type unless generated integrations are disabled.
594    /// - A path that does not parse as a Rust type surfaces as
595    ///   [`CodeGenError::InvalidTypePath`] at generation (`.compile()`) time.
596    /// - The per-element impls are deduplicated within a single generation, but
597    ///   the *same* crate-local type used as a `repeated` element across two
598    ///   separate `compile()` invocations in one crate emits the impl twice (a
599    ///   duplicate-impl `E0119`). Generate from a single `compile()`, use
600    ///   distinct element types, or disable generated integrations and provide
601    ///   them once in the defining crate.
602    Custom(String),
603}
604
605impl BytesRepr {
606    /// The owned Rust type path emitted for a `bytes` field with this
607    /// representation.
608    ///
609    /// `ctx` and `nesting` route the default `Vec<u8>` through the package-root
610    /// import registry; `Bytes` and a custom path are emitted fully qualified.
611    ///
612    /// # Errors
613    ///
614    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
615    /// as a Rust type.
616    pub(crate) fn type_path(
617        &self,
618        resolver: &imports::ImportResolver,
619        ctx: &context::CodeGenContext,
620        nesting: usize,
621    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
622        use quote::quote;
623        match self {
624            BytesRepr::Vec => {
625                let vec = resolver.vec_at(ctx, nesting);
626                Ok(quote! { #vec<u8> })
627            }
628            BytesRepr::Bytes => Ok(quote! { ::buffa::bytes::Bytes }),
629            BytesRepr::Custom(path) => parse_custom_type_path(path),
630        }
631    }
632
633    /// Whether this is the default `Vec<u8>` representation, which keeps the
634    /// `Vec`-specialized fast paths (in-place `merge_bytes`, `clear()`, native
635    /// `Arbitrary`) instead of the generic `ProtoBytes` ones.
636    pub(crate) fn is_default(&self) -> bool {
637        matches!(self, BytesRepr::Vec)
638    }
639}
640
641/// The owned Rust collection a proto `map<K, V>` field maps to in generated
642/// owned structs.
643///
644/// The default is [`HashMap`](MapRepr::HashMap) (`std::collections::HashMap`, or
645/// `hashbrown::HashMap` under `no_std`). [`BTreeMap`](MapRepr::BTreeMap) selects
646/// the buffa-provided `alloc::collections::BTreeMap` for deterministic iteration
647/// order with no extra dependency or consumer code.
648/// [`Custom`](MapRepr::Custom) substitutes any map that satisfies the
649/// `buffa::map_codec::MapStorage` bound — for example a crate-local newtype
650/// wrapping `indexmap::IndexMap`.
651///
652/// Unlike the `repeated` knob (which wraps the element type and needs a `*`
653/// placeholder template), a map type is always `path<K, V>` with both
654/// parameters positional and buffa-resolved, so a custom path is a plain type
655/// path (e.g. `"::my_crate::OrderedMap"`) with no placeholder.
656///
657/// Select a representation through `buffa_build`'s `map_type` /
658/// `map_type_custom` builder methods. The wire format is identical regardless of
659/// the collection; only the in-memory owned type changes.
660#[derive(Debug, Clone, PartialEq, Eq, Default)]
661#[non_exhaustive]
662pub enum MapRepr {
663    /// `::buffa::__private::HashMap<K, V>` — the default. Generated output is
664    /// byte-identical to a build without the knob.
665    #[default]
666    HashMap,
667    /// `::buffa::alloc::collections::BTreeMap<K, V>` — buffa-provided, no extra
668    /// dependency, deterministic key order (so encoded bytes are stable across
669    /// runs). The key type must be `Ord`, which every proto map key type
670    /// (integers, bool, string) satisfies.
671    BTreeMap,
672    /// A custom map named by a fully-qualified Rust type path (e.g.
673    /// `"::my_crate::OrderedMap"`). The named type must satisfy
674    /// `buffa::map_codec::MapStorage` and be a **crate-local newtype** (a foreign
675    /// map cannot implement the buffa-owned reflection / serde traits).
676    ///
677    /// # Limitations
678    ///
679    /// - The path is a plain type path applied as `path<K, V>` — it must **not**
680    ///   include the `<K, V>` parameters or a `*` placeholder. A path that does
681    ///   not parse as a Rust type surfaces as [`CodeGenError::InvalidTypePath`]
682    ///   at generation (`.compile()`) time.
683    /// - The newtype must implement `buffa::map_codec::MapStorage` plus the
684    ///   derive / `FromIterator` / `ReflectMap` / serde / `arbitrary` bounds
685    ///   listed on that trait's docs (the canonical list). JSON and `arbitrary`
686    ///   now work for every proto map key/value type regardless of the container.
687    ///   The buffa-provided [`BTreeMap`](MapRepr::BTreeMap) already satisfies every
688    ///   bound, so prefer it unless you need a specific foreign map.
689    Custom(String),
690}
691
692impl MapRepr {
693    /// The owned Rust map type emitted for a `map<K, V>` field with this
694    /// representation, given the already-resolved key and value type tokens.
695    ///
696    /// `ctx` and `nesting` route the default `HashMap` through the package-root
697    /// import registry; `BTreeMap` and a custom path are emitted fully
698    /// qualified.
699    ///
700    /// # Errors
701    ///
702    /// Returns [`CodeGenError::InvalidTypePath`] if a custom path does not parse
703    /// as a Rust type.
704    pub(crate) fn type_path(
705        &self,
706        key: &proc_macro2::TokenStream,
707        value: &proc_macro2::TokenStream,
708        resolver: &imports::ImportResolver,
709        ctx: &context::CodeGenContext,
710        nesting: usize,
711    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
712        use quote::quote;
713        match self {
714            MapRepr::HashMap => {
715                let hm = resolver.hashmap_at(ctx, nesting);
716                Ok(quote! { #hm<#key, #value> })
717            }
718            MapRepr::BTreeMap => Ok(quote! { ::buffa::alloc::collections::BTreeMap<#key, #value> }),
719            MapRepr::Custom(path) => {
720                let ty = parse_custom_map_path(path)?;
721                Ok(quote! { #ty<#key, #value> })
722            }
723        }
724    }
725
726    /// Whether this is the default `HashMap` representation, whose generated
727    /// output is byte-identical to a build without the knob.
728    pub(crate) fn is_default(&self) -> bool {
729        matches!(self, MapRepr::HashMap)
730    }
731}
732
733/// The owned smart pointer a singular message field's `buffa::MessageField`
734/// wraps in generated owned structs.
735///
736/// The default is [`Inline`](PointerRepr::Inline); it was `Box` before 0.9.
737/// [`Custom`](PointerRepr::Custom)
738/// substitutes any pointer that satisfies the `buffa::ProtoBox<T>` bound — for
739/// example a `smallbox`-style pointer that stores small messages inline.
740/// Because the pointer *wraps* the message type, its path is a **template**
741/// containing a `*` placeholder for the message type (e.g.
742/// `"::smallbox::SmallBox<*, ::smallbox::space::S4>"` or
743/// `"::my_crate::SmallBox<*>"`).
744///
745/// Because `buffa::ProtoBox` is buffa-owned, a *foreign* pointer cannot
746/// implement it directly (orphan rule) — the template must name a crate-local
747/// newtype, mirroring the `ProtoString` newtype expectation.
748///
749/// Select a representation through `buffa_build`'s `box_type_custom` builder
750/// method. The wire format is identical regardless of the pointer; view types
751/// are unaffected. Applies to singular message fields and **boxed** oneof
752/// message/group variants (a variant opted into inline storage via
753/// `unboxed_oneof_fields` takes precedence and gets no pointer). Repeated
754/// message fields use a collection, not a pointer.
755#[derive(Debug, Clone, PartialEq, Eq, Default)]
756#[non_exhaustive]
757pub enum PointerRepr {
758    /// `::buffa::alloc::boxed::Box<T>` (inside `MessageField<T>`). The opt-out
759    /// from the `Inline` default for large or rarely-set submessages, via
760    /// `box_type_in(PointerRepr::Box, paths)` (or `box_type(PointerRepr::Box)`
761    /// to restore the pre-0.9 global default).
762    Box,
763    /// `::buffa::Inline<T>` — store the message directly in the parent struct,
764    /// no heap allocation. `MessageField<T, Inline<T>>` is laid out as
765    /// `Option<T>`. The default.
766    ///
767    /// Recursion-aware: a singular field that would form an infinite-size cycle
768    /// (directly, mutually, or via an
769    /// [`unbox_oneof`](CodeGenConfig::unboxed_oneof_fields)-inlined oneof
770    /// variant) is silently kept on `Box`, so the default is always sized. An
771    /// *exact-path* `Inline` rule that names a recursive field is rejected at
772    /// codegen time.
773    #[default]
774    Inline,
775    /// A custom pointer named by a Rust type-path **template** with a `*`
776    /// placeholder for the message type. Must satisfy `buffa::ProtoBox<T>` and
777    /// be a crate-local newtype.
778    ///
779    /// # Limitations
780    ///
781    /// - The template must contain at least one `*`; a template that omits it
782    ///   surfaces as [`CodeGenError::MissingWildcard`], and one whose
783    ///   substitution does not parse as [`CodeGenError::InvalidTypePath`], at
784    ///   generation (`.compile()`) time.
785    /// - `Rc` / `Arc` and other shared/COW pointers are unusable: the decoder
786    ///   merges in place (needs `DerefMut`), so only an exclusively-owned
787    ///   pointer (heap `Box`, inline `SmallBox`) can implement `ProtoBox`.
788    /// - An inline pointer inflates the parent struct per field, so select it
789    ///   per field/prefix, never as a blanket default.
790    /// - On a **boxed oneof variant** under the `arbitrary` feature, the custom
791    ///   pointer must implement `arbitrary::Arbitrary` (the oneof enum derives it
792    ///   and stores the pointer directly in the variant). The singular-field path
793    ///   needs no such impl — `MessageField` constructs the pointer itself.
794    /// - With JSON generation enabled, custom pointers do not need
795    ///   `serde::Serialize` or `serde::Deserialize`: singular message fields
796    ///   and message-valued oneof variants serialize the pointee, while decode
797    ///   paths construct the pointer through `ProtoBox`.
798    Custom(String),
799}
800
801impl PointerRepr {
802    /// The owned `MessageField<...>` type emitted for a singular message field
803    /// with this representation, given the resolved inner message type tokens
804    /// and the `MessageField` path from the resolver.
805    ///
806    /// # Errors
807    ///
808    /// Returns [`CodeGenError::MissingWildcard`] if a custom template omits `*`,
809    /// or [`CodeGenError::InvalidTypePath`] if it does not parse once the message
810    /// type is substituted.
811    pub(crate) fn type_path(
812        &self,
813        message_field: &proc_macro2::TokenStream,
814        inner: &proc_macro2::TokenStream,
815    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
816        use quote::quote;
817        match self {
818            PointerRepr::Box => Ok(quote! { #message_field<#inner> }),
819            PointerRepr::Inline => Ok(quote! { #message_field<#inner, ::buffa::Inline<#inner>> }),
820            PointerRepr::Custom(template) => {
821                let ptr = parse_wildcard_type_path(template, inner)?;
822                Ok(quote! { #message_field<#inner, #ptr> })
823            }
824        }
825    }
826
827    /// The fully-qualified `::buffa::MessageField::<...>` path for a
828    /// `::some(value)` construction of a singular message field with this
829    /// representation: `<inner>` for `Box` (the pointer param defaults), or
830    /// `<inner, ptr>` for a custom pointer. The view→owned conversion uses this
831    /// so the constructed `MessageField` matches the field's declared type.
832    ///
833    /// # Errors
834    ///
835    /// As [`type_path`](Self::type_path) for a custom template.
836    pub(crate) fn some_path(
837        &self,
838        inner: &proc_macro2::TokenStream,
839    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
840        use quote::quote;
841        match self {
842            PointerRepr::Box => Ok(quote! { ::buffa::MessageField::<#inner> }),
843            PointerRepr::Inline => {
844                Ok(quote! { ::buffa::MessageField::<#inner, ::buffa::Inline<#inner>> })
845            }
846            PointerRepr::Custom(template) => {
847                let ptr = parse_wildcard_type_path(template, inner)?;
848                Ok(quote! { ::buffa::MessageField::<#inner, #ptr> })
849            }
850        }
851    }
852
853    /// The bare pointer type wrapping `inner` for a **boxed oneof variant**
854    /// (`Box<inner>` by default, or the custom pointer). Unlike
855    /// [`type_path`](Self::type_path) this is the pointer alone, not wrapped in
856    /// `MessageField`, because a oneof enum stores the pointer directly in the
857    /// variant.
858    ///
859    /// # Errors
860    ///
861    /// As [`type_path`](Self::type_path) for a custom template.
862    pub(crate) fn pointer_type(
863        &self,
864        inner: &proc_macro2::TokenStream,
865    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
866        use quote::quote;
867        match self {
868            PointerRepr::Box => Ok(quote! { ::buffa::alloc::boxed::Box<#inner> }),
869            PointerRepr::Inline => Ok(quote! { ::buffa::Inline<#inner> }),
870            PointerRepr::Custom(template) => parse_wildcard_type_path(template, inner),
871        }
872    }
873
874    /// Construct the pointer from a value expression for a boxed oneof variant:
875    /// `Box::new(value)` (byte-identical default) or the fully-qualified
876    /// `<Ptr as ProtoBox<inner>>::new(value)` for a custom pointer (so an
877    /// inherent `new` on the pointer can't shadow the trait method).
878    ///
879    /// # Errors
880    ///
881    /// As [`type_path`](Self::type_path) for a custom template.
882    pub(crate) fn pointer_new(
883        &self,
884        inner: &proc_macro2::TokenStream,
885        value: &proc_macro2::TokenStream,
886    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
887        use quote::quote;
888        match self {
889            PointerRepr::Box => Ok(quote! { ::buffa::alloc::boxed::Box::new(#value) }),
890            PointerRepr::Inline => Ok(quote! { ::buffa::Inline(#value) }),
891            PointerRepr::Custom(template) => {
892                let ptr = parse_wildcard_type_path(template, inner)?;
893                Ok(quote! { <#ptr as ::buffa::ProtoBox<#inner>>::new(#value) })
894            }
895        }
896    }
897}
898
899/// The owned Rust collection a proto `repeated` field maps to in generated
900/// owned structs.
901///
902/// The default is [`Vec`](RepeatedRepr::Vec) (`Vec<T>`).
903/// [`Custom`](RepeatedRepr::Custom) substitutes any collection that satisfies
904/// the `buffa::ProtoList<T>` bound — for example a crate-local newtype wrapping
905/// a `SmallVec`-backed inline collection. Unlike the scalar `string`/`bytes`
906/// knobs the custom collection *wraps* the element type, so its path is a
907/// **template** containing a `*` placeholder where the element type is
908/// substituted (e.g. `"::my_crate::SmallList<*>"`).
909///
910/// Because `buffa::ProtoList` is buffa-owned, a *foreign* collection cannot
911/// implement it directly (orphan rule) — the template must always name a
912/// crate-local newtype, mirroring the `ProtoString` newtype expectation.
913///
914/// Select a representation through `buffa_build`'s `repeated_type_custom`
915/// builder method. The wire format is identical regardless of the collection;
916/// view types keep borrowing `&[T]`.
917#[derive(Debug, Clone, PartialEq, Eq, Default)]
918#[non_exhaustive]
919pub enum RepeatedRepr {
920    /// `::buffa::alloc::vec::Vec<T>` — the default. Keeps the `Vec`-specialized
921    /// fast paths (in-place `push`/`reserve`/`clear`, native `Arbitrary`)
922    /// instead of the generic `ProtoList` ones, so generated output for the
923    /// default is byte-identical to a build without the knob.
924    #[default]
925    Vec,
926    /// A custom collection named by a Rust type-path **template** with a `*`
927    /// placeholder for the element type (e.g. `"::my_crate::SmallList<*>"`). The
928    /// named type must satisfy `buffa::ProtoList<T>` and be a **crate-local
929    /// newtype** (a foreign collection cannot implement the buffa-owned
930    /// `ProtoList`).
931    ///
932    /// # Limitations
933    ///
934    /// - The template must contain at least one `*`; the element type is
935    ///   substituted for every `*` before the result is parsed as a Rust type.
936    ///   A template that omits `*` surfaces as
937    ///   [`CodeGenError::MissingListPlaceholder`], and one whose substitution
938    ///   does not parse as [`CodeGenError::InvalidTypePath`], at generation
939    ///   (`.compile()`) time.
940    /// - A custom collection always needs a crate-local newtype — this is not
941    ///   limited to the reflection path. The generated decode and clear code
942    ///   require `Field: ProtoList`, so even a binary-only build cannot use a
943    ///   foreign collection directly.
944    /// - Under reflection / vtable the newtype must implement
945    ///   `buffa_descriptor`'s `ReflectList` (a `Vec`-backed newtype can delegate
946    ///   to the inner `Vec<T>: ReflectList`). Under JSON it must implement
947    ///   `serde::Serialize` / `Deserialize`; under the `arbitrary` feature,
948    ///   `arbitrary::Arbitrary` (derivable on a newtype).
949    /// - A `repeated <self-type>` field becomes `Collection<Self>`, so the
950    ///   collection must be heap-backed; an inline collection (`SmallVec<[Self;
951    ///   N]>`) would be infinitely sized and fail to compile.
952    Custom(String),
953}
954
955impl RepeatedRepr {
956    /// The owned Rust collection type emitted for a `repeated` field with this
957    /// representation, given the already-resolved element type tokens.
958    ///
959    /// `ctx` and `nesting` route the default `Vec` through the package-root
960    /// import registry; a custom template has its `*` placeholders replaced by
961    /// `elem` and the result is parsed and emitted fully qualified.
962    ///
963    /// # Errors
964    ///
965    /// Returns [`CodeGenError::MissingListPlaceholder`] if a custom template
966    /// omits `*`, or [`CodeGenError::InvalidTypePath`] if it does not parse as a
967    /// Rust type once the element is substituted.
968    pub(crate) fn type_path(
969        &self,
970        elem: &proc_macro2::TokenStream,
971        resolver: &imports::ImportResolver,
972        ctx: &context::CodeGenContext,
973        nesting: usize,
974    ) -> Result<proc_macro2::TokenStream, CodeGenError> {
975        use quote::quote;
976        match self {
977            RepeatedRepr::Vec => {
978                let vec = resolver.vec_at(ctx, nesting);
979                Ok(quote! { #vec<#elem> })
980            }
981            RepeatedRepr::Custom(template) => parse_custom_list_path(template, elem),
982        }
983    }
984
985    /// Whether this is the default `Vec` representation, which keeps the
986    /// `Vec`-specialized fast paths instead of the generic `ProtoList` ones.
987    pub(crate) fn is_default(&self) -> bool {
988        matches!(self, RepeatedRepr::Vec)
989    }
990}
991
992/// How much reflection support generated types get.
993///
994/// Selected through `buffa_build`'s `reflect_mode` builder method (or the
995/// `protoc-gen-reallyme-buffa` `reflect_mode=` option). All modes need the consuming
996/// crate to depend on `buffa-descriptor` with its `reflect` feature and on
997/// `std`; the call site is `foo.reflect().get(fd)` regardless of mode.
998#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
999#[non_exhaustive]
1000pub enum ReflectMode {
1001    /// No reflection impls.
1002    #[default]
1003    Off,
1004    /// `Reflectable::reflect()` round-trips the message through a
1005    /// `DynamicMessage` (encode → decode → boxed handle). Smaller generated
1006    /// code; pays an allocation and a re-encode per `reflect()` call.
1007    Bridge,
1008    /// `impl ReflectMessage` directly on the owned and view types, and
1009    /// `Reflectable::reflect()` borrows `self` with no round-trip. Larger
1010    /// generated code; near-free reflective access. Does not require view
1011    /// generation — with views off, only the owned impls are emitted.
1012    VTable,
1013}
1014
1015impl ReflectMode {
1016    /// Apply this mode to a [`CodeGenConfig`] (sets `generate_reflection` /
1017    /// `generate_reflection_vtable`). Used by the `buffa-build` and
1018    /// `protoc-gen-reallyme-buffa` front-ends.
1019    pub fn apply(self, config: &mut CodeGenConfig) {
1020        let (reflection, vtable) = match self {
1021            ReflectMode::Off => (false, false),
1022            ReflectMode::Bridge => (true, false),
1023            ReflectMode::VTable => (true, true),
1024        };
1025        config.generate_reflection = reflection;
1026        config.generate_reflection_vtable = vtable;
1027    }
1028}
1029
1030/// A path-scoped protobuf editions feature override, applied by mutating the
1031/// parsed descriptors before generation (see
1032/// [`feature_overrides`](CodeGenConfig::feature_overrides)).
1033///
1034/// Editions unification models proto2 and proto3 as editions with fixed
1035/// feature defaults, so an override's semantics are "what this proto would
1036/// say had it been migrated to editions and this feature set at this path".
1037/// Each variant is admitted only once buffa's codegen, runtime, and
1038/// validation handle the descriptor states it can create — the enum is the
1039/// allowlist. Overrides never change the wire format.
1040#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1041#[non_exhaustive]
1042pub enum FeatureOverride {
1043    /// Override `features.enum_type` for matching enums or enum fields.
1044    ///
1045    /// An enum-type path mutates the enum's own descriptor (a spec-valid
1046    /// editions construct that also flows into the embedded reflection
1047    /// pool); a field path injects a field-level override that buffa
1048    /// resolves onto the field, in both generated code and the
1049    /// descriptor-driven codecs. `enum_type` is not a legal field target in
1050    /// the spec, so other runtimes reading the exported descriptors ignore a
1051    /// field path.
1052    EnumType(EnumTypeOverride),
1053}
1054
1055impl FeatureOverride {
1056    /// The editions feature name this override sets, as spelled in
1057    /// `google.protobuf.FeatureSet` (e.g. for diagnostics).
1058    #[must_use]
1059    pub fn feature_name(&self) -> &'static str {
1060        match self {
1061            Self::EnumType(_) => "enum_type",
1062        }
1063    }
1064
1065    /// The feature value this override sets, as spelled in the descriptor
1066    /// enum (e.g. for diagnostics).
1067    #[must_use]
1068    pub fn value_name(&self) -> &'static str {
1069        match self {
1070            Self::EnumType(EnumTypeOverride::Open) => "OPEN",
1071        }
1072    }
1073}
1074
1075/// Supported values for [`FeatureOverride::EnumType`].
1076///
1077/// Only `OPEN` is currently supported — closing an open enum would
1078/// reintroduce closed-enum unknown-value routing on fields that never had
1079/// it, a combination buffa's codegen does not yet validate or test.
1080#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1081#[non_exhaustive]
1082pub enum EnumTypeOverride {
1083    /// `features.enum_type = OPEN`: matching closed enum fields generate as
1084    /// `EnumValue<E>`, making unknown wire values directly visible as
1085    /// `EnumValue::Unknown(n)`.
1086    Open,
1087}
1088
1089/// How a message's binary [`Message`](https://docs.rs/reallyme-buffa/latest/buffa/trait.Message.html)
1090/// implementation is generated. Select it with
1091/// [`CodeGenConfig::codec_strategy`] and [`CodeGenConfig::codec_strategy_in`].
1092///
1093/// The strategy changes only the code that sizes, writes and decodes a message
1094/// in the binary wire format. It never changes the wire format, and JSON, text,
1095/// view and reflection code are generated the same way under either.
1096#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1097#[non_exhaustive]
1098pub enum CodecStrategy {
1099    /// Emit code specialised to each message: the fastest code, and the
1100    /// largest. The default.
1101    #[default]
1102    Unrolled,
1103    /// Emit one static table per message and forward `Message` to interpreters
1104    /// shared by every message, in the `buffa` crate. On a large schema it
1105    /// makes the compiled code about 40% smaller at `opt-level = "z"`; a
1106    /// message that cannot use it keeps its size. It costs run time on messages
1107    /// made of many small fields. The guide's "Smaller generated code" section
1108    /// has the measurements.
1109    ///
1110    /// Not every message can use it. These stay [`Unrolled`](Self::Unrolled):
1111    ///
1112    /// - a message with a group field;
1113    /// - the message type of a group field;
1114    /// - a message that uses the `MessageSet` wire format;
1115    /// - a message with extension ranges, when JSON code is generated and
1116    ///   unknown fields are preserved;
1117    /// - a message with a `map` field, when `map_entries_omit_defaults` is
1118    ///   set: the table writes both fields of every entry;
1119    /// - a message with a field of a non-default string, bytes, or collection
1120    ///   type, such as `use_bytes_type`, `string_type`, `bytes_type`,
1121    ///   `repeated_type`, and a custom `map_type` select. `HashMap` and
1122    ///   `BTreeMap` maps are supported; a `map` whose keys or values are of a
1123    ///   non-default string or bytes type is not;
1124    /// - a message that holds, in a singular, repeated, `oneof`, or map value
1125    ///   field, a message of the same run that has a `bytes` field of a
1126    ///   non-default type, or that holds one. The table decodes from one
1127    ///   contiguous slice, so it would copy `bytes::Bytes` fields that
1128    ///   unrolled code decoding from a `Bytes` shares with the input.
1129    ///
1130    /// A table message may hold any other message, including as a member of a
1131    /// `oneof` and as a `map` value. It reaches a child that is a table
1132    /// message through the child's table, and any other child, whether it is
1133    /// [`Unrolled`](Self::Unrolled), generated by another crate, or a
1134    /// well-known type, through the child's `Message` impl, which costs a
1135    /// function call per child. Selecting a message does not select the
1136    /// messages it holds, and keeping a child [`Unrolled`](Self::Unrolled) does
1137    /// not keep the messages that hold it unrolled: to keep a whole path
1138    /// specialised, set its holders to `Unrolled` too.
1139    ///
1140    /// A table message differs from an unrolled one in these ways. A field that
1141    /// declares a length past the end of its enclosing message fails at once
1142    /// with `DecodeError::UnexpectedEof`, where unrolled code can report a
1143    /// different error for the same rejected input; a child reached through its
1144    /// `Message` impl is read from the slice of the nearest enclosing table
1145    /// message, so it is bounded there. `clear()` resets the message to its
1146    /// default, which releases the capacity of its strings, vectors and maps,
1147    /// where unrolled code keeps it.
1148    /// Decoding gathers a `Buf` that is not contiguous into one buffer first.
1149    /// Encoding into any sink other than the cursor that `Message::encode` and
1150    /// its siblings write a `BufMut` through, meaning a `Rope`, a sink defined
1151    /// outside `buffa`, or a `BufMut` passed straight to `Message::write_to`,
1152    /// stages each child reached through its `Message` impl in a scratch
1153    /// buffer, and a `Rope` copies it again and cannot share the `bytes`
1154    /// fields inside it by reference count. Codegen cannot see the fields of a
1155    /// message from another crate, so a table message that holds one with a
1156    /// `bytes` field of a non-default type copies it on decode. The well-known
1157    /// type `google.protobuf.Any` is one, because its `value` is
1158    /// `bytes::Bytes`. To keep the payload shared with a `Bytes` input, set the
1159    /// holder to [`Unrolled`](Self::Unrolled) with `codec_strategy_in`.
1160    ///
1161    /// A message that another crate or codegen run uses as the type of a group
1162    /// or editions `DELIMITED` field must not be selected, because
1163    /// `Message::merge_field` on a table message cannot gather a
1164    /// non-contiguous buffer, and the default group decoding calls it. Codegen
1165    /// sees only the group fields of its own run.
1166    ///
1167    /// Codegen reports the messages that fall back in one
1168    /// [`CodeGenWarning::TableCodecFallbackSummary`]. The table code needs Rust
1169    /// 1.77 or later, and contains `unsafe` code inside `buffa` macros, so it
1170    /// compiles under `#![forbid(unsafe_code)]`.
1171    Table,
1172}
1173
1174/// Why some messages selected for [`CodecStrategy::Table`] fell back to
1175/// [`CodecStrategy::Unrolled`], for
1176/// [`CodeGenWarning::TableCodecFallbackSummary`].
1177#[derive(Debug, Clone, PartialEq, Eq)]
1178#[non_exhaustive]
1179pub struct TableCodecFallbackReason {
1180    /// The reason as a predicate, such as `has a group field`. The wording is for
1181    /// people and may change between releases.
1182    pub reason: String,
1183    /// The proto paths of all of them, with a leading dot, in declaration
1184    /// order.
1185    pub messages: Vec<String>,
1186}
1187
1188/// Configuration for code generation.
1189#[derive(Debug, Clone)]
1190#[non_exhaustive]
1191pub struct CodeGenConfig {
1192    /// Generate recursive `Zeroize`, `ZeroizeOnDrop` and `Drop` for messages,
1193    /// oneofs and the owned storage of their views. Borrowed input is not wiped.
1194    /// Requires the runtime's `zeroize` feature, guarded custom bytes/string
1195    /// representations, and unknown-field storage disabled. Collections default
1196    /// to wipe-owning runtime collections; referenced messages must also support cleanup.
1197    /// Reflection uses borrowed `InspectMessage` access without snapshots.
1198    /// Arbitrary construction uses an early cleanup owner and a depth bound.
1199    pub generate_zeroize: bool,
1200    /// Proto path prefixes selecting messages for recursive cleanup.
1201    /// `.` selects every generated message, including nested messages.
1202    pub zeroize_messages: Vec<String>,
1203    /// Message prefixes whose views reject JSON serialization before writing output.
1204    /// The restriction propagates to containing messages, including through maps
1205    /// and imported descriptors. Owned-message JSON is unchanged. `.` selects all.
1206    /// Every rule must match a known message, including imported messages.
1207    pub deny_view_json: Vec<String>,
1208    /// Permit message selectors that belong to another directory-scoped plugin
1209    /// request. Such selectors still produce warnings. Keep this disabled when
1210    /// validating the complete project so misspelled security rules are errors.
1211    pub allow_unmatched_message_rules: bool,
1212
1213    /// Whether to generate borrowed view types (`MyMessageView<'a>`) in
1214    /// addition to owned types.
1215    pub generate_views: bool,
1216    /// Whether to additionally generate the lazy view family
1217    /// (`MyMessageLazyView<'a>`) alongside the eager views (default: false).
1218    ///
1219    /// Lazy views implement `buffa::LazyMessageView`: `decode_lazy` performs
1220    /// a single non-recursive scan, recording singular/repeated message
1221    /// fields as undecoded byte ranges (`LazyMessageFieldView` /
1222    /// `LazyRepeatedView`) that decode on access — reading a few fields of
1223    /// many sub-messages no longer allocates or recurses into untouched
1224    /// sub-trees. The eager `MyMessageView` family is unchanged (output is
1225    /// byte-identical with or without this flag), so eager and lazy views
1226    /// coexist and generic `MessageView` consumers never silently inherit
1227    /// deferred validation.
1228    ///
1229    /// Semantics of the lazy family:
1230    ///
1231    /// - **Eager carve-outs**: groups / editions `DELIMITED` fields (no
1232    ///   length prefix to defer), oneof message variants, and map message
1233    ///   values use the eager view types.
1234    /// - **Merge preserved**: a singular message field split across wire
1235    ///   occurrences is recorded as fragments and merged on access.
1236    /// - **Budgets flow**: the recursion depth, unknown-field allowance, and
1237    ///   element-memory budget remaining at each deferred field are recorded
1238    ///   and replayed per access (a per-subtree approximation of the shared
1239    ///   budgets).
1240    /// - **Deferred validation**: malformed deferred bytes error on access,
1241    ///   from the fallible `to_owned_message`, and as a serde error from the
1242    ///   view `Serialize` impl. `ViewEncode` replays recorded fragments
1243    ///   **without validating them**.
1244    /// - No `ReflectMessage`, `OwnedView`, or text-format surface — use the
1245    ///   eager family for those.
1246    ///
1247    /// Requires [`generate_views`](Self::generate_views) (the lazy family
1248    /// reuses the eager view-oneof enums and eager sub-view types); with
1249    /// views disabled the flag is ignored with a warning.
1250    pub lazy_views: bool,
1251    /// Whether to preserve unknown fields (default: true).
1252    ///
1253    /// Path-scoped overrides go in
1254    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in);
1255    /// the last matching rule wins over this global default.
1256    ///
1257    /// A message with preservation off has no `__buffa_unknown_fields` field,
1258    /// and with it loses everything built on that field: its `ExtensionSet`
1259    /// impl (typed extension access), `ReflectMessage::unknown_fields`,
1260    /// extension round-tripping through textproto, and `[ext]` keys in JSON.
1261    pub preserve_unknown_fields: bool,
1262    /// Path-scoped overrides for
1263    /// [`preserve_unknown_fields`](Self::preserve_unknown_fields). Each entry is
1264    /// `(proto_path_prefix, enabled)`, with a leading dot (`".pkg.Msg"`).
1265    ///
1266    /// Matching uses the same proto-segment-aware prefix rules as
1267    /// `bytes_fields` and `unboxed_oneof_fields`: a rule covers the message it
1268    /// names *and every message nested inside it*, and `"."` covers everything.
1269    /// A rule naming a nested message does not cover its enclosing message. The
1270    /// **last** matching rule wins, so a later, more specific entry can carve a
1271    /// nested message back out of an earlier, broader one. Granularity is
1272    /// per-message: the flag gates whether the struct carries
1273    /// `__buffa_unknown_fields`. Preservation is a property of each message
1274    /// type, not of a value graph, so a preserved message's sub-messages keep
1275    /// their own unknown fields only if their types are covered too.
1276    ///
1277    /// A rule that matches no generated message produces a
1278    /// [`CodeGenWarning::PreserveUnknownFieldsRuleMatchedNothing`].
1279    pub preserve_unknown_fields_in: Vec<(String, bool)>,
1280    /// Whether generated JSON deserializers reject unknown fields
1281    /// (default: `false`, lenient).
1282    ///
1283    /// Path-scoped overrides go in
1284    /// [`deny_unknown_json_fields_in`](Self::deny_unknown_json_fields_in);
1285    /// the last matching rule wins over this global default. With
1286    /// [`generate_json`](Self::generate_json) off the setting changes nothing
1287    /// and produces a [`CodeGenWarning::DenyUnknownJsonFieldsRequiresJson`].
1288    ///
1289    /// A strict message rejects every key that matches none of its fields,
1290    /// under either the JSON name or the proto name, with serde's
1291    /// `unknown_field` error. `"[pkg.ext]"` keys of a message that has
1292    /// extension ranges and preserves unknown fields still go through the
1293    /// extension registry, where `JsonParseOptions::strict_extension_keys`
1294    /// governs unregistered ones. A message with extension ranges and
1295    /// preservation off rejects them like any other unknown key.
1296    pub deny_unknown_json_fields: bool,
1297    /// Path-scoped overrides for
1298    /// [`deny_unknown_json_fields`](Self::deny_unknown_json_fields). Each
1299    /// entry is `(proto_path_prefix, enabled)`, with a leading dot
1300    /// (`".pkg.Msg"`).
1301    ///
1302    /// Matching uses the same proto-segment-aware prefix rules as
1303    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in): a
1304    /// rule covers the message it names *and every message nested inside
1305    /// it*, `"."` covers everything, and the **last** matching rule wins, so
1306    /// a later, more specific entry can carve a nested message back out of an
1307    /// earlier, broader one.
1308    ///
1309    /// A rule that matches no generated message produces a
1310    /// [`CodeGenWarning::DenyUnknownJsonFieldsRuleMatchedNothing`].
1311    pub deny_unknown_json_fields_in: Vec<(String, bool)>,
1312    /// Whether to derive `serde::Serialize` / `serde::Deserialize` on
1313    /// generated message structs and enum types, and emit `#[serde(with = "...")]`
1314    /// attributes for proto3 JSON's special scalar encodings (int64 as quoted
1315    /// string, bytes as base64, etc.).
1316    ///
1317    /// When this is `true`, the downstream crate must depend on `serde` and
1318    /// must enable the `buffa/json` feature for the runtime helpers.
1319    ///
1320    /// Oneof fields use `#[serde(flatten)]` with custom `Serialize` /
1321    /// `Deserialize` impls so that each variant appears as a top-level
1322    /// JSON field (proto3 JSON inline oneof encoding).
1323    pub generate_json: bool,
1324    /// Whether to emit `#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]`
1325    /// on generated message structs and enum types. An enum with a
1326    /// `[deprecated = true]` variant gets a generated impl under the same
1327    /// `cfg` instead, because the derive would warn on that variant.
1328    ///
1329    /// When this is `true`, the downstream crate must add `arbitrary` as an
1330    /// optional dependency and enable the `buffa/arbitrary` feature. The
1331    /// downstream crate's Cargo feature that gates `arbitrary` must be named
1332    /// exactly `"arbitrary"` — the generated `cfg_attr` uses that literal
1333    /// string and cannot be customized. This applies to both the struct-level
1334    /// `derive(Arbitrary)` and the per-field `#[arbitrary(with = ...)]`
1335    /// attributes described below.
1336    ///
1337    /// For a field whose `bytes_fields` or `string_fields` rule selects a
1338    /// non-default type, codegen emits `#[arbitrary(with = ...)]` using
1339    /// helpers in `::buffa::__private`, so the substituted type needs no
1340    /// `Arbitrary` impl. This covers singular, optional, repeated and oneof
1341    /// fields, and the key and value of a `map` field.
1342    pub generate_arbitrary: bool,
1343    /// Proto paths of the messages and enums whose generated `Debug`
1344    /// implementation is omitted, so that the consuming crate can write its
1345    /// own.
1346    ///
1347    /// For messages a rule is a proto-segment-aware prefix: `".pkg.Msg"`
1348    /// matches that message and the messages nested inside it, `".pkg"`
1349    /// matches every message in the package and its sub-packages, and `"."`
1350    /// matches every message. The oneof enums of a matched message lose
1351    /// their `Debug` with it. An enum loses its `Debug` only when a rule is
1352    /// its exact name, such as `".pkg.Level"`. View types keep theirs.
1353    ///
1354    /// A matched enum does not compile until the crate implements `Debug`
1355    /// for it, because `buffa::Enumeration` requires `Debug`. A matched
1356    /// message needs an impl when an unmatched message or oneof holds it,
1357    /// because their generated `Debug` formats it, and whenever reflection
1358    /// is generated, because `ReflectElement` requires `Debug`.
1359    ///
1360    /// A rule that matches no generated message and names no generated enum
1361    /// produces [`CodeGenWarning::SkipDebugRuleMatchedNothing`].
1362    pub skip_debug: Vec<String>,
1363    /// External type path mappings.
1364    ///
1365    /// Each entry maps either a fully-qualified protobuf package prefix
1366    /// (e.g., `".my.common"`) to a Rust module path (e.g.,
1367    /// `"::common_protos"`), or a single type FQN (e.g.,
1368    /// `".my.common.Shared"`) to a full Rust type path (e.g.,
1369    /// `"::shared_types::Shared"`). Matched types reference the extern Rust
1370    /// path instead of being generated, allowing shared proto packages to be
1371    /// compiled once in a dedicated crate and referenced from others. An
1372    /// exact type-FQN entry wins over a covering package prefix; otherwise
1373    /// the longest matching prefix wins.
1374    ///
1375    /// The proto side must be `"."` (every type) or a fully-qualified name:
1376    /// a leading dot, then protobuf identifiers separated by single dots,
1377    /// with no trailing dot. [`generate`] does not validate entries, and an
1378    /// entry in another form matches no type; a caller that fills this field
1379    /// directly should pass each name through
1380    /// [`normalize_extern_path_proto_name`], as `protoc-gen-reallyme-buffa` and
1381    /// `buffa-build` do.
1382    ///
1383    /// Well-known types (`google.protobuf.*`) are automatically mapped to
1384    /// `::buffa_types::google::protobuf::*` without needing an explicit
1385    /// entry here. To override with a custom implementation, add an
1386    /// `extern_path` for `.google.protobuf` pointing to your crate.
1387    ///
1388    /// When JSON generation is enabled, an external message routed through a
1389    /// ProtoJSON container helper must implement
1390    /// `buffa::json_helpers::ProtoElemJson` so generated containers can apply
1391    /// ProtoJSON encoding and reject null elements/values. This includes
1392    /// external wrapper types in repeated/map fields and external message
1393    /// values in bytes-keyed maps; ordinary message containers use serde
1394    /// directly.
1395    pub extern_paths: Vec<(String, String)>,
1396    /// Ordered (proto-path-prefix, [`BytesRepr`]) rules selecting the Rust type
1397    /// for `bytes` fields. Later rules win, so a broad rule (e.g. `"."` →
1398    /// `Bytes`) can be refined by a more specific one. Fields matching no rule
1399    /// use `Vec<u8>`.
1400    ///
1401    /// A rule is a prefix of a fully-qualified field path, matched on whole
1402    /// path segments, and starts with a dot: `".my.pkg.Msg.data"`,
1403    /// `".my.pkg.Msg"`, `".my.pkg"`, or `"."` for every field. Codegen does
1404    /// not add the dot (`buffa-build` does), and a path without it matches no
1405    /// field. A rule that does not match a field of a generated message
1406    /// produces [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
1407    pub bytes_fields: Vec<(String, BytesRepr)>,
1408    /// Ordered (proto-path-prefix, [`StringRepr`]) rules selecting the Rust type
1409    /// for `string` fields. Later rules win, so a broad rule (e.g. `"."` →
1410    /// `SmolStr`) can be refined by a more specific one
1411    /// (`".my.pkg.Msg.field"` → `CompactString`). Fields matching no rule use
1412    /// `String`. The path is matched with the same proto-segment-aware prefix
1413    /// logic as [`bytes_fields`](Self::bytes_fields).
1414    ///
1415    /// Applies to singular, optional, and repeated `string` fields, oneof
1416    /// `string` variants, and the `string` keys and values of `map` fields
1417    /// (matched by the map field's path). A rule that does not match a field
1418    /// of a generated message produces
1419    /// [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
1420    pub string_fields: Vec<(String, StringRepr)>,
1421    /// Custom `bytes` and `string` representations, named by Rust type path
1422    /// exactly as in their [`BytesRepr::Custom`] / [`StringRepr::Custom`]
1423    /// rules, whose protobuf JSON goes through `buffa::json_helpers::ProtoBytesJson`
1424    /// or `ProtoStringJson`.
1425    ///
1426    /// Every field of a listed type then serializes and deserializes through
1427    /// the type's policy: singular, optional, repeated and oneof fields, `map`
1428    /// values, and the corresponding fields of generated views and owned views.
1429    /// Paths are compared as parsed Rust types, so whitespace does not matter.
1430    /// A listed type that no unshadowed representation rule names produces
1431    /// [`CodeGenError::JsonPolicyTypeMatchedNothing`]; a listed `string` type
1432    /// used as a key of an enum-valued `map` is a
1433    /// [`CodeGenError::JsonPolicyMapKey`]. Unlisted
1434    /// custom types keep their existing JSON behavior.
1435    pub json_policy_types: Vec<String>,
1436    /// Emit element JSON/reflection impls for custom bytes/string types.
1437    ///
1438    /// Disable this when the representation's defining crate already supplies
1439    /// `ProtoElemJson`, `ReflectElement`, `ReflectMapKey` and `InspectElement` as needed. This
1440    /// permits shared foreign representations and separate generation calls
1441    /// without violating coherence or emitting duplicate implementations.
1442    /// Missing implementations remain compile errors in the generated code.
1443    pub emit_custom_type_impls: bool,
1444    /// Ordered (proto-path-prefix, [`MapRepr`]) rules selecting the owned Rust
1445    /// map collection for `map` fields. Later rules win, with the same
1446    /// proto-segment-aware prefix matching as [`bytes_fields`](Self::bytes_fields)
1447    /// (`"."` matches every field). Fields matching no rule use `HashMap<K, V>`.
1448    ///
1449    /// Independent of the element/value representation: a `map` field's key and
1450    /// value types are chosen by the usual scalar/string/bytes/message rules,
1451    /// and this option changes only the surrounding collection. A rule that
1452    /// does not match a field of a generated message produces
1453    /// [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
1454    pub map_fields: Vec<(String, MapRepr)>,
1455    /// Ordered (proto-path-prefix, [`PointerRepr`]) rules selecting the owned
1456    /// smart pointer for singular message fields (the pointer inside
1457    /// `MessageField<T>`). Later rules win, same proto-segment-aware prefix
1458    /// matching as [`bytes_fields`](Self::bytes_fields). Fields matching no rule
1459    /// use `Box<T>`.
1460    ///
1461    /// Applies to singular (and proto2 optional/required) message fields only —
1462    /// not repeated message fields (a collection) or oneof message variants.
1463    pub pointer_fields: Vec<(String, PointerRepr)>,
1464    /// Ordered (proto-path-prefix, [`RepeatedRepr`]) rules selecting the owned
1465    /// Rust collection for `repeated` fields. Later rules win, with the same
1466    /// proto-segment-aware prefix matching as [`bytes_fields`](Self::bytes_fields)
1467    /// (`"."` matches every field). Fields matching no rule use `Vec<T>`.
1468    ///
1469    /// Applies only to `repeated` fields (not `map`, whose collection stays
1470    /// the configured map type). The element type is chosen by the usual
1471    /// scalar/string/bytes/message rules and substituted into the collection
1472    /// template. A rule that does not match a field of a generated message
1473    /// produces [`CodeGenWarning::FieldTypeRuleMatchedNothing`].
1474    pub repeated_fields: Vec<(String, RepeatedRepr)>,
1475    /// Path-scoped editions feature overrides, applied by mutating the parsed
1476    /// descriptors before generation.
1477    ///
1478    /// Each entry pairs a fully-qualified proto path prefix with a
1479    /// [`FeatureOverride`]. Paths are matched with the same
1480    /// proto-segment-aware logic as [`bytes_fields`](Self::bytes_fields): a
1481    /// rule may name a type (`".my.pkg.E"`), a field (`".my.pkg.Msg.e"`), a
1482    /// package/message prefix, or `"."` for everything the override targets.
1483    /// Leading dots are optional, trailing dots are ignored, and
1484    /// blank/all-dot entries match nothing. Map enum values match the outer
1485    /// map field path; oneof enum variants match the direct field path.
1486    ///
1487    /// The mutated descriptors are what codegen — and, under reflection, the
1488    /// embedded descriptor pool — see, so runtime reflection and
1489    /// descriptor-driven dynamic JSON stay consistent with the generated
1490    /// types for both enum-scoped and field-scoped rules; see each variant's
1491    /// docs for its semantics. A rule that matches nothing is reported as
1492    /// [`CodeGenWarning::FeatureOverrideMatchedNothing`] through
1493    /// [`generate_with_diagnostics`] (the plain [`generate`] entry point
1494    /// discards warnings). Overrides never change the wire format. The
1495    /// default is empty, so generated output and semantics are unchanged
1496    /// unless configured.
1497    pub feature_overrides: Vec<(String, FeatureOverride)>,
1498    /// Fully-qualified proto paths whose message-typed oneof variants should
1499    /// **not** be wrapped in `Box<T>`. By default every message/group oneof
1500    /// variant is boxed (so recursive types compile); entries here opt matching
1501    /// variants out, storing the message inline in the enum.
1502    ///
1503    /// Each entry is a proto path prefix matched with the same
1504    /// proto-segment-aware logic as [`bytes_fields`](Self::bytes_fields)
1505    /// (`"."` matches every variant). Recursive variants cannot be stored
1506    /// inline (the type would be unsized): an entry naming one *exactly* is
1507    /// rejected at codegen time, while a broader prefix entry silently keeps
1508    /// recursive variants boxed and inlines the rest.
1509    pub unboxed_oneof_fields: Vec<String>,
1510    /// Honor `features.utf8_validation = NONE` by emitting `Vec<u8>` / `&[u8]`
1511    /// for such string fields instead of `String` / `&str`.
1512    ///
1513    /// When `false` (the default), buffa emits `String` for all string fields
1514    /// and **validates UTF-8 on decode** — stricter than proto2 requires, but
1515    /// ergonomic and safe.
1516    ///
1517    /// When `true`, string fields with `utf8_validation = NONE` (all proto2
1518    /// strings by default, and editions fields that opt into `NONE`) become
1519    /// `Vec<u8>` / `&[u8]`. Decode skips validation; the caller decides at the
1520    /// call site whether to `std::str::from_utf8` (checked) or
1521    /// `from_utf8_unchecked` (trusted-input fast path). This is the only
1522    /// sound Rust mapping when strings may actually contain non-UTF-8 bytes.
1523    ///
1524    /// **This is a breaking change for proto2** — enable only for new code or
1525    /// when profiling identifies UTF-8 validation as a bottleneck.
1526    pub strict_utf8_mapping: bool,
1527    /// Permit `option message_set_wire_format = true` on input messages.
1528    ///
1529    /// MessageSet is a legacy Google-internal wire format that wraps each
1530    /// extension in a group structure instead of using regular field tags.
1531    /// When `false` (the default), encountering such a message is a codegen
1532    /// error — the flag exists to make MessageSet use explicit, since the
1533    /// format is obsolete outside of interop with very old Google protos.
1534    pub allow_message_set: bool,
1535    /// Whether to emit `impl buffa::text::TextFormat` on generated message
1536    /// structs for textproto (human-readable text format) encoding/decoding.
1537    ///
1538    /// When this is `true`, the downstream crate must enable the `buffa/text`
1539    /// feature for the runtime encoder/decoder.
1540    pub generate_text: bool,
1541    /// Whether the per-package `.mod.rs` stitcher emits
1542    /// `__buffa::register_types(&mut TypeRegistry)`.
1543    ///
1544    /// Default `true`. The fn aggregates `Any` type entries and extension
1545    /// entries for every message in the package. Set to `false` for
1546    /// crates that don't use extensions/`Any`, or that hand-roll
1547    /// registration (e.g. `buffa-types`' `register_wkt_types`, which
1548    /// knows the JSON-Any `is_wkt` special-casing the generic fn does
1549    /// not). The per-message `__*_JSON_ANY` / `__*_TEXT_ANY` consts are
1550    /// still emitted; only the aggregating fn is suppressed.
1551    pub emit_register_fn: bool,
1552    /// Emit one `<dotted.package>.rs` per proto package instead of the
1553    /// per-proto-file content set plus `<pkg>.mod.rs` stitcher.
1554    ///
1555    /// The single file inlines what the stitcher would otherwise `include!`,
1556    /// producing the same `__buffa::{view,oneof,ext,...}` module structure.
1557    /// Intended for Buf Schema Registry generated SDKs, whose `lib.rs`
1558    /// synthesis builds the module tree from `<dotted.package>.rs` filenames.
1559    ///
1560    /// Under `strategy: directory` this only sees one directory's files per
1561    /// invocation, so the input module must be `PACKAGE_DIRECTORY_MATCH`-clean
1562    /// (one package per directory) for the output to be complete. BSR-hosted
1563    /// modules satisfy this by lint default. If a package spans multiple
1564    /// directories, separate invocations each emit their own `<pkg>.rs` and
1565    /// the last write wins — silent partial output, not a codegen error.
1566    pub file_per_package: bool,
1567    /// Custom attributes to inject on generated types (messages, enums, and
1568    /// oneof enums — the latter matched on the oneof's own path,
1569    /// `.my.pkg.MyMessage.my_oneof`).
1570    ///
1571    /// Each entry is `(proto_path, attribute)`. The `proto_path` is matched
1572    /// as a prefix against the fully-qualified proto name: `"."` applies to
1573    /// all types, `".my.pkg"` to types in that package, `".my.pkg.MyMessage"`
1574    /// to a specific type. The `attribute` is one or more outer Rust
1575    /// attributes, each written with its `#[...]` (e.g.,
1576    /// `"#[derive(serde::Serialize)]"`). [`generate`] returns
1577    /// [`CodeGenError::InvalidCustomAttribute`] for any other string, an
1578    /// empty one included. The same rule holds for the five attribute lists
1579    /// below.
1580    ///
1581    /// When using a custom `serde::Serialize` derive, follow the requirements
1582    /// documented by `buffa_build::Config::type_attribute`: disable
1583    /// unknown-field preservation for generated messages and enable the
1584    /// `json` feature for buffa's `EnumValue` and `MessageField` serde
1585    /// implementations. Do not combine a custom derive with generated JSON
1586    /// implementations.
1587    pub type_attributes: Vec<(String, String)>,
1588    /// Custom attributes to inject on generated struct fields.
1589    ///
1590    /// Each entry is `(proto_path, attribute)`. The `proto_path` is matched
1591    /// as a prefix against the fully-qualified field path (e.g.,
1592    /// `".my.pkg.MyMessage.my_field"`). `"."` applies to all fields. Oneof
1593    /// variants are matched as `".my.pkg.MyMessage.my_oneof.variant"`; the
1594    /// struct field holding the oneof is not reached, see
1595    /// `oneof_struct_field_attributes`.
1596    pub field_attributes: Vec<(String, String)>,
1597    /// Custom attributes to inject on generated message structs only (not enums).
1598    ///
1599    /// Same path-matching semantics as `type_attributes`, but only applied to
1600    /// message structs, not enum types. Useful for struct-only attributes like
1601    /// `#[serde(default)]`.
1602    pub message_attributes: Vec<(String, String)>,
1603    /// Custom attributes to inject on generated enum types only (not messages).
1604    ///
1605    /// Same path-matching semantics as `type_attributes`, but only applied to
1606    /// enum types. Useful for enum-only attributes like
1607    /// `#[derive(strum::EnumIter)]` when the user does not want to apply the
1608    /// same attribute to every message in the matched scope.
1609    pub enum_attributes: Vec<(String, String)>,
1610    /// Custom attributes to inject on generated oneof enums only (not messages,
1611    /// not regular enums).
1612    ///
1613    /// Same path-matching semantics as `type_attributes`, matched against the
1614    /// oneof's fully-qualified path (`.pkg.Message.oneof_name`). Useful when a
1615    /// oneof needs a different attribute set than the surrounding types — e.g.
1616    /// applying `#[derive(serde::Serialize)]` to oneofs while a separate
1617    /// `enum_attributes` entry puts a different serde derive on the regular
1618    /// enums. When the surrounding messages use the same custom derive, follow
1619    /// the `buffa_build::Config::type_attribute` requirements for unknown
1620    /// fields and the `json` feature.
1621    pub oneof_attributes: Vec<(String, String)>,
1622    /// Custom attributes to inject on a message struct's field holding a
1623    /// oneof (the `Option<OneofEnum>` member), not on the oneof's variants or
1624    /// the oneof enum.
1625    ///
1626    /// Same path-matching semantics as `type_attributes`, matched against the
1627    /// oneof's fully-qualified path (`.pkg.Message.oneof_name`).
1628    /// `field_attributes` never reaches this field: on the oneof's path it
1629    /// matches only the variants (`.pkg.Message.oneof_name.variant`).
1630    ///
1631    /// Applies to the owned message struct only; the view structs do not get
1632    /// the attribute.
1633    pub oneof_struct_field_attributes: Vec<(String, String)>,
1634    /// Wrap generated `impl`s in `#[cfg(feature = "...")]` instead of
1635    /// emitting them unconditionally.
1636    ///
1637    /// When `true`, the impls controlled by [`generate_json`],
1638    /// [`generate_views`], and [`generate_text`] are emitted wrapped in
1639    /// `#[cfg(feature = "json" | "views" | "text")]` (or
1640    /// `#[cfg_attr(feature = ..., ...)]` for derives and field attributes)
1641    /// rather than unconditionally. The consuming crate must define matching
1642    /// Cargo features that enable the corresponding runtime support, e.g.:
1643    ///
1644    /// ```toml
1645    /// [features]
1646    /// json  = ["buffa/json", "dep:serde", "dep:serde_json"]
1647    /// views = []
1648    /// text  = ["buffa/text"]
1649    /// ```
1650    ///
1651    /// The [`generate_*`] flags still control *whether* an impl kind is
1652    /// emitted at all — this flag only controls whether it is `cfg`-gated.
1653    /// `generate_arbitrary` is always `cfg_attr`-gated on
1654    /// `feature = "arbitrary"` regardless of this flag, because `arbitrary`
1655    /// is an optional dependency by design.
1656    ///
1657    /// When [`generate_reflection`](Self::generate_reflection) is also on, the
1658    /// reflection impls are gated on `feature = "reflect"` alongside
1659    /// json/views/text. To gate *only* reflection without gating json/views/text,
1660    /// use [`gate_reflect_on_crate_feature`](Self::gate_reflect_on_crate_feature)
1661    /// instead.
1662    ///
1663    /// This is the mechanism that lets `buffa-descriptor` and `buffa-types`
1664    /// ship every impl while keeping the codegen toolchain
1665    /// (`buffa-codegen`/`buffa-build`/`protoc-gen-reallyme-buffa`) lean: those crates
1666    /// depend on `buffa-descriptor` with `default-features = false` and so
1667    /// don't pull `serde`/`serde_json`/`base64`. Most consumers don't need
1668    /// this — they decide at build-script time whether to generate JSON, and
1669    /// if they say yes, they want `impl Serialize` to just exist.
1670    ///
1671    /// [`generate_json`]: Self::generate_json
1672    /// [`generate_views`]: Self::generate_views
1673    /// [`generate_text`]: Self::generate_text
1674    /// [`generate_*`]: Self::generate_json
1675    pub gate_impls_on_crate_features: bool,
1676    /// Generate `with_*` builder-style setter methods for explicit-presence fields.
1677    ///
1678    /// Each explicit-presence scalar, bytes, or enum field gets a
1679    /// `pub fn with_<name>(mut self, value: T) -> Self` method that wraps the
1680    /// value in `Some` and returns `self`, enabling chained construction:
1681    ///
1682    /// ```ignore
1683    /// let req = MyRequest::default()
1684    ///     .with_name("alice")
1685    ///     .with_timeout_ms(30_000);
1686    /// ```
1687    ///
1688    /// **Fields that receive a setter:** proto3 `optional`, proto2 `optional`,
1689    /// and editions fields with `field_presence = EXPLICIT`.
1690    ///
1691    /// **Fields that do not receive a setter:** message fields
1692    /// (`MessageField<T>`), repeated fields, map fields, oneof variant fields,
1693    /// proto2 `required` fields, and any implicit-presence field.
1694    ///
1695    /// There is no `clear_<name>` companion — to clear a field, assign `None`
1696    /// directly: `msg.name = None;`.
1697    ///
1698    /// Defaults to `true`.
1699    pub generate_with_setters: bool,
1700    /// Encode map entries as prost does: leave an entry's key or value out
1701    /// when it holds what a missing field decodes to, and a message value when
1702    /// it encodes to nothing.
1703    ///
1704    /// Off, every entry carries both fields, as the C++ and Java runtimes
1705    /// write them. Decoding reads either; a `-0.0` float value is left out
1706    /// and so decodes as `0.0`. prost leaves out a message value equal to its
1707    /// default, so a value that still encodes a field, such as one with a
1708    /// `required` field at its default, is written here and not by prost.
1709    ///
1710    /// Applies to the owned, view and lazy view encoders of the messages
1711    /// generated in this run: types generated without it, the well-known
1712    /// types and `DynamicMessage` write both fields. With
1713    /// [`CodecStrategy::Table`], messages with a map field keep the unrolled
1714    /// codec, and a [`codec_strategy_in`](Self::codec_strategy_in) rule that
1715    /// selects the table for such a message by its exact path is a
1716    /// [`CodeGenError`]. `buffa_build::Config::map_entries_omit_defaults` has
1717    /// the details.
1718    ///
1719    /// Defaults to `false`.
1720    pub map_entries_omit_defaults: bool,
1721    /// Generate `impl Reflectable` for owned message types (bridge mode).
1722    ///
1723    /// When enabled, each generated message gets an
1724    /// `impl ::buffa_descriptor::reflect::Reflectable` whose `reflect()`
1725    /// round-trips through `DynamicMessage` (encode → decode → reflective
1726    /// handle), and the package's `__buffa::reflect` submodule embeds the
1727    /// `FileDescriptorSet` bytes plus a lazily-built `DescriptorPool`.
1728    ///
1729    /// **Runtime requirements** — the consuming crate must depend on:
1730    /// - `buffa-descriptor` with the `reflect` feature.
1731    /// - `std` (the lazy pool accessor uses `std::sync::OnceLock`).
1732    ///
1733    /// When [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
1734    /// is on, the impls are wrapped in `#[cfg(feature = "reflect")]` so the
1735    /// consuming crate can opt out per build.
1736    ///
1737    /// **Performance** — `reflect()` is one full encode/decode round-trip
1738    /// plus a heap allocation. The first call also pays a one-time pool
1739    /// build cost (linking the embedded `FileDescriptorSet`). For zero-copy
1740    /// reflective access over view types without the round-trip, additionally
1741    /// enable [`generate_reflection_vtable`](Self::generate_reflection_vtable).
1742    ///
1743    /// **Binary size** — by default each package embeds its own copy of the
1744    /// full `FileDescriptorSet` (transitive closure), so a multi-package run
1745    /// duplicates the FDS bytes per package. Enable
1746    /// [`shared_descriptor_pool`](Self::shared_descriptor_pool) to embed one
1747    /// shared copy at the module-tree root instead.
1748    ///
1749    /// Defaults to `false`.
1750    pub generate_reflection: bool,
1751    /// Emit vtable-mode reflection: `impl ReflectMessage` / `impl
1752    /// ReflectElement` on the owned message structs and (when views are
1753    /// generated) the view types, and switch the owned
1754    /// `Reflectable::reflect()` body to borrow `self`
1755    /// (`ReflectCow::Borrowed(self)`) instead of the bridge round-trip.
1756    ///
1757    /// Reflective access then reads struct fields in place — no encode/decode
1758    /// round-trip and no per-field allocation — for both a decoded view and an
1759    /// in-memory owned message.
1760    ///
1761    /// Requires [`generate_reflection`](Self::generate_reflection) (the impls
1762    /// resolve against the same embedded `DescriptorPool`) but not
1763    /// [`generate_views`](Self::generate_views) — with views off, only the
1764    /// owned impls are emitted. Set via [`ReflectMode::VTable`]
1765    /// — front-ends expose it as `buffa_build::Config::reflect_mode` /
1766    /// `protoc-gen-reallyme-buffa`'s `reflect_mode=vtable`.
1767    ///
1768    /// Defaults to `false`.
1769    pub generate_reflection_vtable: bool,
1770    /// Deduplicate the embedded reflection descriptor pool across packages.
1771    ///
1772    /// With [`generate_reflection`](Self::generate_reflection) on, each
1773    /// package normally embeds its own copy of the full-closure
1774    /// `FileDescriptorSet` (`FILE_DESCRIPTOR_SET_BYTES`). For a multi-package
1775    /// run those copies are byte-identical, so the crate carries the same
1776    /// bytes once per package — which dominates generated-crate size for large
1777    /// proto trees.
1778    ///
1779    /// When this is `true`, `generate` instead emits per-package
1780    /// `__buffa::reflect` modules that **delegate** to a single shared
1781    /// `__buffa_fds` module at the module-tree root. Every consumer path
1782    /// (`pkg::descriptor_pool()`, `pkg::FILE_DESCRIPTOR_SET_BYTES`,
1783    /// `pkg::__buffa::reflect::*`) keeps resolving; it just aliases the one
1784    /// shared copy, and all packages observe the same `DescriptorPool`
1785    /// instance.
1786    ///
1787    /// The shared root module itself is emitted by the module-tree builder
1788    /// (`buffa-build`, or `protoc-gen-reallyme-buffa-packaging` with its matching
1789    /// `shared_descriptor_pool=true`), not by `generate`, so this mode
1790    /// requires one of those front-ends to assemble the tree — unless
1791    /// [`shared_descriptor_pool_root`](Self::shared_descriptor_pool_root) is
1792    /// set, in which case the root can live anywhere the caller assembled it.
1793    /// Consumers that wire the per-package modules by hand should leave both
1794    /// `false`/`None` (the default), which keeps the self-contained
1795    /// per-package embedding.
1796    ///
1797    /// Use the same setting for every codegen run assembled into one module
1798    /// tree. Packages generated with this set to `false` keep their own pools
1799    /// even when sibling packages delegate to a shared pool; this mixed setup
1800    /// is not diagnosed.
1801    ///
1802    /// Defaults to `false`. [`generate`] errors when this is on without
1803    /// `generate_reflection`.
1804    pub shared_descriptor_pool: bool,
1805    /// When [`shared_descriptor_pool`](Self::shared_descriptor_pool) is on,
1806    /// use this path to the shared `__buffa_fds` module verbatim instead of
1807    /// computing a `super::`-relative one.
1808    ///
1809    /// The default `super::` path assumes one crate hosts the whole package
1810    /// tree as nested modules. A workspace with one crate per package has no
1811    /// such tree to climb; this field lets the caller point at wherever they
1812    /// assembled [`shared_descriptor_root_module`]'s output instead — a
1813    /// separate crate, a re-exported alias, anything.
1814    ///
1815    /// The target is a contract, not a free-form value: it must be
1816    /// [`shared_descriptor_root_module`]'s output, `pub` and nameable from
1817    /// every package this and every other codegen run in the tree emits,
1818    /// gated the same way as [`reflect_feature_gate`](Self::reflect_feature_gate)
1819    /// if that's set, built against a semver-compatible `buffa-descriptor`,
1820    /// and — like the plugin path's `shared_descriptor_pool` (see the guide's
1821    /// "spans both plugins" note) — contain every message this `generate()`
1822    /// run reflects on. A root missing a type fails at runtime with a
1823    /// `reflect()` lookup panic, not at `generate()` or `cargo build` time.
1824    ///
1825    /// Must be an absolute (`::`-prefixed) or `crate`-relative path of plain
1826    /// `::`-separated identifiers — no generic or parenthesized arguments —
1827    /// since the same string is spliced verbatim at every package depth.
1828    /// [`generate`] rejects a malformed value immediately, before splicing it
1829    /// into generated source. Example: `"::my_shared_fds_crate::__buffa_fds"`.
1830    ///
1831    /// `None` (the default) keeps the `super::`-relative behavior.
1832    pub shared_descriptor_pool_root: Option<String>,
1833    /// Reuse a [`SharedCorpusContext`] built once by
1834    /// [`SharedCorpusContext::new`] instead of re-deriving the corpus-wide
1835    /// oneof/pointer-repr resolution and comment collection on every
1836    /// `generate()` call — the win for a one-crate-per-package workspace that
1837    /// generates each package from one whole-corpus `FileDescriptorSet` with
1838    /// only `extern_paths` varying per call. The context must have been built
1839    /// from the same `files` and the same
1840    /// `unboxed_oneof_fields`/`pointer_fields` as the call using it;
1841    /// `generate` checks and returns
1842    /// [`CodeGenError::SharedCorpusContextMismatch`] otherwise.
1843    ///
1844    /// `None` (the default) recomputes on every call.
1845    pub shared_corpus_context: Option<SharedCorpusContext>,
1846    /// Gate the reflection impls behind a `reflect` crate feature, *without*
1847    /// gating json/views/text (unlike
1848    /// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features),
1849    /// which gates them all together).
1850    ///
1851    /// Used by crates that ship view/text impls unconditionally but want the
1852    /// reflection surface — which pulls a `buffa-descriptor` dependency and
1853    /// `std` — to be opt-in. `buffa-types` is the motivating case: its WKT
1854    /// views are always available, but `impl ReflectMessage` for them is gated
1855    /// behind `buffa-types`'s `reflect` feature.
1856    ///
1857    /// When [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
1858    /// is already on, reflection is gated regardless and this flag is ignored.
1859    ///
1860    /// A low-level knob for crates whose generated code is a public interface
1861    /// (`buffa-types`, the conformance harness). Set directly by `gen_wkt_types`
1862    /// and exposed through `buffa_build::Config::gate_reflect_on_crate_feature`
1863    /// (currently `#[doc(hidden)]`).
1864    ///
1865    /// Defaults to `false`.
1866    pub gate_reflect_on_crate_feature: bool,
1867    /// Emit idiomatic `UpperCamelCase` constant aliases alongside each enum
1868    /// variant.
1869    ///
1870    /// Protobuf style names enum values in `SHOUTY_SNAKE_CASE`, conventionally
1871    /// prefixed with the enum name (`RULE_LEVEL_HIGH`). Those names remain the
1872    /// definitive Rust variants — they are guaranteed unique and valid by
1873    /// protobuf, and existing references (including `Debug` output) are
1874    /// unchanged. When this is enabled, codegen additionally emits associated
1875    /// `const`s with the prefix stripped and the name converted to
1876    /// `UpperCamelCase` (`RULE_LEVEL_HIGH` → `High`), so downstream code can
1877    /// write `RuleLevel::High`.
1878    ///
1879    /// The conversion is lossy, so two values can collide (`FOO_BAR` and
1880    /// `FOO__BAR` both map to `FooBar`). The rule is all-or-nothing per enum:
1881    /// if any two values would collide after conversion, or a value would yield
1882    /// an invalid identifier, **no** aliases are emitted for that enum (a
1883    /// [`CodeGenWarning`] and an enum doc note explain why). This keeps every
1884    /// match either fully `SHOUTY_SNAKE_CASE` or fully idiomatic, never a forced
1885    /// mix.
1886    ///
1887    /// The aliases are associated `const`s, which work in pattern position too:
1888    /// a `match` written entirely against aliases is still exhaustiveness-checked
1889    /// (the "non-exhaustive" error names the underlying `SHOUTY_SNAKE_CASE`
1890    /// variant, since that is the canonical name).
1891    ///
1892    /// Defaults to `true`: the aliases are purely additive (the proto names
1893    /// remain the variants, and `Debug` is unchanged), so enabling by default is
1894    /// backward-compatible, and the all-or-nothing rule guarantees correctness on
1895    /// any enum.
1896    pub idiomatic_enum_aliases: bool,
1897    /// Emit `use`-backed short type names at the package root instead of
1898    /// fully-qualified paths, so generated code reads like hand-written
1899    /// Rust (`pub at: MessageField<Timestamp>` instead of
1900    /// `pub at: ::buffa::MessageField<::buffa_types::google::protobuf::Timestamp>`).
1901    ///
1902    /// Requires [`file_per_package`](Self::file_per_package): only there is
1903    /// the package-root scope a single-writer file whose complete name set
1904    /// is known at generation time. In the multi-file layout the stitcher
1905    /// `include!`-merges every proto's content files into the shared root
1906    /// scope, where emitted `use` directives could collide across files —
1907    /// [`generate`] returns an error for that combination rather than
1908    /// silently ignoring the flag.
1909    ///
1910    /// Off by default; default output is byte-for-byte unchanged. Short
1911    /// names are always backed by an explicit `use` (never glob reliance),
1912    /// are refused when they would collide with the package's own items or
1913    /// names referenced bare by sibling emissions, and fall back to
1914    /// parent-module qualification and then the fully-qualified path. The
1915    /// short-name *assignment* (use block and per-path choices) is computed
1916    /// from a collection pre-pass and is stable under `.proto` file
1917    /// reordering; item order within the file still follows input order,
1918    /// so whole-file output is not reorder-invariant. The pre-pass
1919    /// generates the package twice, roughly doubling codegen time for it.
1920    ///
1921    /// Scope: only package-root *type declarations* (struct fields, oneof
1922    /// `Option` wrappers) are shortened. Impl bodies, nested-message
1923    /// modules, and `__buffa` internals keep fully-qualified paths — the
1924    /// readability payoff lands where consumers look (struct definitions
1925    /// and rustdoc), not in the codec internals.
1926    ///
1927    /// **Experimental** means: the generated-output shape may change
1928    /// between releases (requiring regeneration of checked-in code), and
1929    /// the option itself may be renamed or removed outside semver
1930    /// guarantees.
1931    pub idiomatic_imports: bool,
1932    /// Convert proto field and oneof names to idiomatic snake_case Rust
1933    /// identifiers (`webMessageInfo` → `web_message_info`), matching
1934    /// prost-build's behavior for protos that use camelCase field names.
1935    ///
1936    /// Only the generated *Rust source names* change — struct fields, view
1937    /// accessors, `has_*`/`with_*` methods. Every name-keyed protocol surface
1938    /// keeps the descriptor's names: the wire format keys on field numbers,
1939    /// JSON uses `json_name` (with the original proto name still accepted on
1940    /// parse, per the proto3 JSON spec), text format and reflection lookups
1941    /// use the original proto name. Enum values and message/module names are
1942    /// not affected (see
1943    /// [`idiomatic_enum_aliases`](Self::idiomatic_enum_aliases) for enums),
1944    /// and extension accessors are `SHOUTY_SNAKE_CASE` constants derived
1945    /// independently of this option.
1946    ///
1947    /// Word boundaries match heck's (and therefore prost-build's)
1948    /// segmentation, including acronym handling (`XMLHttpRequest` →
1949    /// `xml_http_request`) and digit-transparent case boundaries
1950    /// (`v2Field` → `v2_field`). The one deliberate divergence from prost:
1951    /// the conversion is insertion-only and never deletes underscores the
1952    /// proto author wrote, so it is the identity on every name that is
1953    /// already a valid snake_case identifier (`_foo` stays `_foo`, where
1954    /// prost emits `foo`).
1955    ///
1956    /// The conversion is lossy, so two members of one message can collide
1957    /// (`userName` and `user_name`). Unlike enum aliases — which are additive
1958    /// `const`s and can simply be suppressed — a field rename replaces the
1959    /// canonical name, so collisions are resolved deterministically instead:
1960    /// a member whose name is already snake_case keeps it, a converted field
1961    /// that collides gets an `_f<field_number>` suffix (`userName = 12` →
1962    /// `user_name_f12`), and a converted oneof that collides keeps its
1963    /// verbatim proto name. If an adjusted field name still collides, the
1964    /// changed members in that collision group fall back to their verbatim
1965    /// proto names. Each adjustment is reported as a
1966    /// [`CodeGenWarning::IdiomaticFieldNamesAdjusted`]. protoc rejects the
1967    /// underlying name collisions for proto3 and editions files (conflicting
1968    /// `json_name`s), so adjustments are only reachable from proto2 inputs.
1969    ///
1970    /// Defaults to `false`: a rename is not backward-compatible for existing
1971    /// consumers of generated camelCase fields, and verbatim emission keeps
1972    /// the `.proto` file the source of truth. Opt in for prost parity.
1973    pub idiomatic_field_names: bool,
1974    /// Crate feature names used by the `#[cfg(feature = "...")]` gates that
1975    /// [`gate_impls_on_crate_features`](Self::gate_impls_on_crate_features)
1976    /// and
1977    /// [`gate_reflect_on_crate_feature`](Self::gate_reflect_on_crate_feature)
1978    /// emit.
1979    ///
1980    /// Defaults to `"json"` / `"views"` / `"text"` / `"reflect"`. Override a
1981    /// name when the consuming crate gates the same concern behind a
1982    /// different feature name (e.g. its JSON support behind a `serde`
1983    /// feature). Inert unless one of the gating flags is on.
1984    pub feature_gate_names: FeatureGateNames,
1985    /// Prefix prepended to every locally-generated Rust type name.
1986    ///
1987    /// With prefix `"Rpc"`, `message User {}` generates `struct RpcUser`,
1988    /// its view becomes `RpcUserView` / `RpcUserOwnedView`, and every
1989    /// cross-reference (fields, oneof variants, maps, extensions) uses the
1990    /// prefixed name. Useful in multi-protocol systems where generated
1991    /// types from different domains would otherwise collide with each
1992    /// other or with a canonical hand-written model.
1993    ///
1994    /// The prefix applies to **message structs and enum types** (top-level
1995    /// and nested, plus their derived view/owned-view types). It does not
1996    /// apply to:
1997    ///
1998    /// - module names (`message Outer` still nests under `pub mod outer`).
1999    ///   A prefix can remove a module's trailing `_`: the nested types of
2000    ///   `message item` are in `item_` beside `struct item`, and in `item`
2001    ///   beside `struct Pbitem`,
2002    /// - oneof enums (structurally namespaced under `__buffa::oneof::`,
2003    ///   named after the oneof declaration, not the message),
2004    /// - types mapped away via [`extern_paths`](Self::extern_paths) or the
2005    ///   automatic well-known-type mapping (their names are owned by the
2006    ///   external crate),
2007    /// - wire-format and JSON output (proto names, `TYPE_URL`s, and JSON
2008    ///   field names are unaffected — this is a pure Rust-identifier
2009    ///   rename).
2010    ///
2011    /// When another codegen run references these prefixed types via its own
2012    /// [`extern_paths`](Self::extern_paths) mapping, the mapped Rust path
2013    /// must spell out the prefixed name (e.g. `::crate_a::RpcUser`) — the
2014    /// proto name carries no prefix, so the mapping is not derived
2015    /// automatically. Prefix-induced name collisions (e.g. `message RpcUser`
2016    /// alongside `message User` with prefix `Rpc`) are not detected here;
2017    /// they surface as ordinary duplicate-definition errors when the
2018    /// generated code is compiled.
2019    ///
2020    /// Must be PascalCase (`[A-Z][A-Za-z0-9]*`) — an ASCII uppercase letter
2021    /// followed by ASCII letters and digits — so the prefixed names stay
2022    /// conventionally cased; generation fails with
2023    /// [`CodeGenError::InvalidTypeNamePrefix`] otherwise. Defaults to `""`
2024    /// (no prefix).
2025    pub type_name_prefix: String,
2026    /// Proto packages to exclude from code generation (default: empty).
2027    ///
2028    /// Each entry is a normalized proto package name without a leading dot
2029    /// (e.g. `"buf.validate"`, `"gnostic.openapi.v3"`). A package matches
2030    /// if it equals an entry exactly or starts with `"<entry>."` — so
2031    /// `"buf.validate"` excludes both `buf.validate` and `buf.validate.priv`.
2032    ///
2033    /// Use this when `.proto` files from option-only packages (e.g.
2034    /// `buf/validate/validate.proto`, gnostic annotations) end up in the
2035    /// generate set via `include_imports` or directory globbing, but you do
2036    /// not want Rust types for those packages. Their descriptors remain in
2037    /// the compilation for type resolution; only code generation is skipped.
2038    ///
2039    /// **If you exclude a package that other kept files reference as a field
2040    /// type**, you must also add an [`extern_path`](Self::extern_paths) mapping
2041    /// for it, or the generated code will contain dangling `super::…::Type`
2042    /// paths that fail to compile ([`CodeGenWarning::ExcludedPackageFieldRef`]
2043    /// names the offending field first).
2044    ///
2045    /// Entries are proto package names with no empty segments (e.g.
2046    /// `"buf.validate"`, `"gnostic.openapi.v3"`); a leading dot is accepted
2047    /// and stripped at generation time. [`generate_with_diagnostics`] rejects
2048    /// anything else, and warns with
2049    /// [`CodeGenWarning::ExcludePackageMatchedNothing`] for an entry that
2050    /// matches no package in the input.
2051    pub exclude_packages: Vec<String>,
2052    /// The [`CodecStrategy`] of every message that no
2053    /// [`codec_strategy_in`](Self::codec_strategy_in) rule covers (default:
2054    /// [`CodecStrategy::Unrolled`]).
2055    ///
2056    /// Under [`CodecStrategy::Table`] a message that cannot use the table
2057    /// stays unrolled, and codegen reports one
2058    /// [`CodeGenWarning::TableCodecFallbackSummary`] for the run.
2059    pub codec_strategy: CodecStrategy,
2060    /// Path-scoped overrides for [`codec_strategy`](Self::codec_strategy).
2061    /// Each entry is `(proto_path_prefix, strategy)`, with a leading dot
2062    /// (`".pkg.Msg"`).
2063    ///
2064    /// Matching uses the same proto-segment-aware prefix rules as
2065    /// [`preserve_unknown_fields_in`](Self::preserve_unknown_fields_in): a rule
2066    /// covers the message it names *and every message nested inside it*, `"."`
2067    /// covers everything, and the **last** matching rule wins.
2068    ///
2069    /// A [`CodecStrategy::Table`] rule that covers a message that cannot use
2070    /// the table keeps it unrolled and counts it in the
2071    /// [`CodeGenWarning::TableCodecFallbackSummary`]. If the rule names the
2072    /// message by its exact path, that is an error instead, because the rule
2073    /// asked for something impossible. A rule that matches no generated message
2074    /// produces a [`CodeGenWarning::CodecStrategyRuleMatchedNothing`].
2075    ///
2076    /// A rule does not extend to the messages a message holds; see
2077    /// [`CodecStrategy::Table`].
2078    pub codec_strategy_in: Vec<(String, CodecStrategy)>,
2079}
2080
2081impl Default for CodeGenConfig {
2082    fn default() -> Self {
2083        Self {
2084            generate_zeroize: false,
2085            zeroize_messages: Vec::new(),
2086            deny_view_json: Vec::new(),
2087            allow_unmatched_message_rules: false,
2088            generate_views: true,
2089            lazy_views: false,
2090            preserve_unknown_fields: true,
2091            preserve_unknown_fields_in: Vec::new(),
2092            deny_unknown_json_fields: false,
2093            deny_unknown_json_fields_in: Vec::new(),
2094            generate_json: false,
2095            generate_arbitrary: false,
2096            skip_debug: Vec::new(),
2097            extern_paths: Vec::new(),
2098            bytes_fields: Vec::new(),
2099            string_fields: Vec::new(),
2100            json_policy_types: Vec::new(),
2101            emit_custom_type_impls: true,
2102            map_fields: Vec::new(),
2103            pointer_fields: Vec::new(),
2104            repeated_fields: Vec::new(),
2105            feature_overrides: Vec::new(),
2106            unboxed_oneof_fields: Vec::new(),
2107            strict_utf8_mapping: false,
2108            allow_message_set: false,
2109            generate_text: false,
2110            emit_register_fn: true,
2111            file_per_package: false,
2112            type_attributes: Vec::new(),
2113            field_attributes: Vec::new(),
2114            message_attributes: Vec::new(),
2115            enum_attributes: Vec::new(),
2116            oneof_attributes: Vec::new(),
2117            oneof_struct_field_attributes: Vec::new(),
2118            gate_impls_on_crate_features: false,
2119            generate_with_setters: true,
2120            map_entries_omit_defaults: false,
2121            generate_reflection: false,
2122            generate_reflection_vtable: false,
2123            shared_descriptor_pool: false,
2124            shared_descriptor_pool_root: None,
2125            shared_corpus_context: None,
2126            gate_reflect_on_crate_feature: false,
2127            idiomatic_enum_aliases: true,
2128            idiomatic_imports: false,
2129            idiomatic_field_names: false,
2130            feature_gate_names: FeatureGateNames::default(),
2131            type_name_prefix: String::new(),
2132            exclude_packages: Vec::new(),
2133            codec_strategy: CodecStrategy::Unrolled,
2134            codec_strategy_in: Vec::new(),
2135        }
2136    }
2137}
2138
2139impl CodeGenConfig {
2140    /// Whether any [`FeatureOverride::EnumType`] rule is configured — the
2141    /// gate for the open-enum declared-default machinery (which can only
2142    /// fire when a closed enum has been opened by such a rule).
2143    pub(crate) fn has_enum_type_overrides(&self) -> bool {
2144        self.feature_overrides
2145            .iter()
2146            .any(|(_, o)| matches!(o, FeatureOverride::EnumType(_)))
2147    }
2148
2149    /// Active [`feature_gates::FeatureGates`] for this config.
2150    ///
2151    /// Recomputed on each call (cheap — three boolean ANDs); call once at
2152    /// the top of a generation function and thread through, or call inline
2153    /// at each use site, whichever reads better.
2154    pub(crate) fn feature_gates(&self) -> feature_gates::FeatureGates<'_> {
2155        feature_gates::FeatureGates::for_config(self)
2156    }
2157
2158    /// The crate feature the reflection surface is gated behind, or `None`
2159    /// when reflection is unconditional.
2160    ///
2161    /// Front-ends emitting the shared descriptor root module (see
2162    /// [`shared_descriptor_root_module`] and
2163    /// [`shared_descriptor_pool`](Self::shared_descriptor_pool)) must gate it
2164    /// with this exact value, so the root module and the per-package
2165    /// delegations that reference it appear and disappear together.
2166    #[must_use]
2167    pub fn reflect_feature_gate(&self) -> Option<&str> {
2168        self.feature_gates().reflect
2169    }
2170
2171    /// Returns the Rust name of a locally generated type:
2172    /// [`type_name_prefix`](Self::type_name_prefix), then the proto simple
2173    /// name, with [`idents::escape_type_name`] applied to the two joined.
2174    /// This is the name the type is declared with and the name in the type
2175    /// map.
2176    pub(crate) fn prefixed_type_name(&self, proto_name: &str) -> String {
2177        idents::local_type_name(&self.type_name_prefix, proto_name)
2178    }
2179
2180    /// Validate [`type_name_prefix`](Self::type_name_prefix): empty (no
2181    /// prefix) or PascalCase (`[A-Z][A-Za-z0-9]*`), so `{prefix}{TypeName}`
2182    /// is always a valid, conventionally-cased identifier that does not
2183    /// trip `non_camel_case_types` in consumer crates.
2184    pub(crate) fn validate_type_name_prefix(&self) -> Result<(), CodeGenError> {
2185        let prefix = &self.type_name_prefix;
2186        let valid = prefix.is_empty()
2187            || (prefix.starts_with(|c: char| c.is_ascii_uppercase())
2188                && prefix.chars().all(|c| c.is_ascii_alphanumeric()));
2189        if valid {
2190            Ok(())
2191        } else {
2192            Err(CodeGenError::InvalidTypeNamePrefix {
2193                prefix: prefix.clone(),
2194            })
2195        }
2196    }
2197}
2198
2199/// Compute the effective extern path list by starting with user-provided
2200/// mappings and adding the default WKT mapping if appropriate.
2201///
2202/// The default mapping `".google.protobuf" → "::buffa_types::google::protobuf"`
2203/// is added unless:
2204/// - The user already provided an extern_path covering `.google.protobuf`
2205/// - Any of the files being generated are in the `google.protobuf` package
2206///   (i.e., we're building `buffa-types` itself)
2207pub(crate) fn effective_extern_paths(
2208    file_descriptors: &[FileDescriptorProto],
2209    files_to_generate: &[String],
2210    config: &CodeGenConfig,
2211) -> Vec<(String, String)> {
2212    let mut paths = config.extern_paths.clone();
2213
2214    // Only an EXACT .google.protobuf mapping suppresses auto-injection.
2215    // A sub-package mapping like .google.protobuf.compiler does NOT cover
2216    // WKTs like Timestamp — resolve_extern_prefix's longest-prefix matching
2217    // lets both coexist, so we still inject the parent mapping.
2218    let has_wkt_mapping = paths.iter().any(|(proto, _)| proto == ".google.protobuf");
2219
2220    if !has_wkt_mapping {
2221        // Check if we're generating google.protobuf files ourselves
2222        // (e.g., building buffa-types). If so, don't auto-map.
2223        let generating_wkts = file_descriptors
2224            .iter()
2225            .filter(|fd| {
2226                fd.name
2227                    .as_deref()
2228                    .is_some_and(|n| files_to_generate.iter().any(|f| f == n))
2229            })
2230            .any(|fd| fd.package.as_deref() == Some("google.protobuf"));
2231
2232        if !generating_wkts {
2233            paths.push((
2234                ".google.protobuf".to_string(),
2235                "::buffa_types::google::protobuf".to_string(),
2236            ));
2237        }
2238    }
2239
2240    paths
2241}
2242
2243/// Compute the effective file-level extern path list.
2244///
2245/// File-level mappings route a specific `.proto` file to a Rust module root,
2246/// taking priority over the package-level mappings from
2247/// [`effective_extern_paths`]. They exist to resolve a structural problem:
2248/// `descriptor.proto` is in the same `google.protobuf` package as the
2249/// well-known types (`Timestamp`, `Any`, …), but its types live in
2250/// `buffa-descriptor`, not `buffa-types`. A single package-keyed
2251/// `.google.protobuf` extern_path can route the package to one crate or the
2252/// other; it can't split it. The file-level mapping splits it.
2253///
2254/// Auto-injected mappings (when not suppressed):
2255///
2256/// | Proto file | Rust module |
2257/// |---|---|
2258/// | `google/protobuf/descriptor.proto` | `::buffa_descriptor::generated::descriptor` |
2259/// | `google/protobuf/compiler/plugin.proto` | `::buffa_descriptor::generated::compiler` |
2260///
2261/// Suppression conditions, evaluated **per file**:
2262///
2263/// - **A user-provided `extern_path` covers the file's package.** That
2264///   override has covered the file's types since the package mapping was
2265///   introduced; auto-injecting a higher-priority file-level mapping would
2266///   silently redirect them away from the user's crate. Matching is via
2267///   the same longest-prefix logic the package resolver uses, so both an
2268///   exact `.google.protobuf` mapping and a sub-package
2269///   `.google.protobuf.compiler` mapping suppress the entries they cover —
2270///   `.google.protobuf` suppresses both, `.google.protobuf.compiler`
2271///   suppresses only `plugin.proto`.
2272/// - **The proto file itself is in `files_to_generate`.** When building
2273///   `buffa-descriptor` (or any local copy of `descriptor.proto`), its types
2274///   must resolve to the local module, not externally.
2275///
2276/// Currently internal-only — there is no `CodeGenConfig` field for
2277/// user-provided *file-level* mappings. The user-facing `extern_path` API is
2278/// keyed by proto package *or* type FQN (per-type overrides, issue #111);
2279/// per-file overrides may be added later as a public feature if a concrete
2280/// need arises.
2281pub(crate) fn effective_file_extern_paths(
2282    files_to_generate: &[String],
2283    config: &CodeGenConfig,
2284) -> Vec<(String, String)> {
2285    // (proto file path, proto package, Rust module root). The package is
2286    // recorded alongside the file so the user-override suppression check
2287    // is per-file: a `.google.protobuf.compiler` extern_path covers only
2288    // `plugin.proto`, while `.google.protobuf` covers both.
2289    const DESCRIPTOR_FILES: [(&str, &str, &str); 2] = [
2290        (
2291            "google/protobuf/descriptor.proto",
2292            "google.protobuf",
2293            "::buffa_descriptor::generated::descriptor",
2294        ),
2295        (
2296            "google/protobuf/compiler/plugin.proto",
2297            "google.protobuf.compiler",
2298            "::buffa_descriptor::generated::compiler",
2299        ),
2300    ];
2301
2302    DESCRIPTOR_FILES
2303        .into_iter()
2304        .filter(|(proto_file, package, _)| {
2305            // Yield to a user package-level extern_path that already covers
2306            // this file's package: anyone who wrote
2307            // `extern_path(".google.protobuf", "::my_crate")` (or a
2308            // sub-package mapping) today routes these types to their crate;
2309            // the auto-injected file-level mapping must not silently
2310            // outrank it.
2311            if context::resolve_extern_prefix(package, &config.extern_paths).is_some() {
2312                return false;
2313            }
2314            // Don't externalize a file we're generating locally.
2315            !files_to_generate.iter().any(|f| f == proto_file)
2316        })
2317        .map(|(proto_file, _, rust_module)| (proto_file.to_string(), rust_module.to_string()))
2318        .collect()
2319}
2320
2321/// One CamelCase collision: a target identifier and the proto value names that
2322/// would all convert onto it.
2323///
2324/// Part of [`CodeGenWarning::IdiomaticAliasesSuppressed`].
2325#[derive(Debug, Clone, PartialEq, Eq)]
2326#[non_exhaustive]
2327pub struct AliasConflict {
2328    /// The `UpperCamelCase` identifier the colliding values map to.
2329    pub camel_target: String,
2330    /// The proto value names that convert onto `camel_target` (includes a
2331    /// literal variant name when an alias would shadow it).
2332    pub proto_values: Vec<String>,
2333}
2334
2335/// A non-fatal diagnostic produced during code generation.
2336///
2337/// Returned by [`generate_with_diagnostics`]. Render the human-readable form via
2338/// the [`Display`](core::fmt::Display) impl (e.g. `cargo:warning={warning}`), or
2339/// match on the variant for programmatic handling. The enum and its variants are
2340/// `#[non_exhaustive]` so new diagnostic kinds and fields can be added without a
2341/// breaking change.
2342#[derive(Debug, Clone, PartialEq, Eq)]
2343#[non_exhaustive]
2344pub enum CodeGenWarning {
2345    /// An explicitly permitted selector was absent from this scoped request.
2346    #[non_exhaustive]
2347    ZeroizeRuleMatchedNothing { rule: String },
2348    /// An explicitly permitted view selector was absent from this scoped request.
2349    #[non_exhaustive]
2350    ViewJsonRuleMatchedNothing { rule: String },
2351    /// View JSON restrictions cannot apply without both JSON and view generation.
2352    #[non_exhaustive]
2353    ViewJsonRulesRequireJsonAndViews,
2354    /// Idiomatic CamelCase aliases were suppressed for an enum because two or
2355    /// more proto values collide after conversion, or a value would convert to
2356    /// an invalid identifier. The enum's `SHOUTY_SNAKE_CASE` variants are
2357    /// unaffected.
2358    #[non_exhaustive]
2359    IdiomaticAliasesSuppressed {
2360        /// The Rust name of the affected enum.
2361        enum_name: String,
2362        /// Each collision, by target identifier. Empty if the only problem was
2363        /// invalid identifiers.
2364        conflicts: Vec<AliasConflict>,
2365        /// Proto values that would convert to an invalid Rust identifier.
2366        invalid: Vec<String>,
2367    },
2368    /// A field or oneof accessor on a generated `FooOwnedView` wrapper was
2369    /// suppressed because the proto name collides with one of the wrapper's
2370    /// reserved method names (`decode`, `view`, `bytes`, …). The field stays
2371    /// fully accessible through `view()` on the wrapper (or
2372    /// `OwnedView::reborrow`).
2373    #[non_exhaustive]
2374    OwnedViewAccessorSuppressed {
2375        /// The Rust name of the wrapper type (e.g. `FooOwnedView`).
2376        wrapper_name: String,
2377        /// The proto field or oneof name whose accessor was suppressed.
2378        field_name: String,
2379    },
2380    /// `lazy_views` was requested with `generate_views` disabled; the lazy
2381    /// family reuses the eager view-oneof enums and eager sub-view types, so
2382    /// no lazy views were generated. Emitted once per generation run.
2383    #[non_exhaustive]
2384    LazyViewsRequireViews,
2385    /// [`deny_unknown_json_fields`](CodeGenConfig::deny_unknown_json_fields), or a
2386    /// [`deny_unknown_json_fields_in`](CodeGenConfig::deny_unknown_json_fields_in)
2387    /// rule, was set with [`generate_json`](CodeGenConfig::generate_json)
2388    /// disabled. There are no JSON deserializers to make strict, so the
2389    /// setting changed nothing — forgetting `generate_json` is the likelier
2390    /// mistake than a wrong path, and without this the option is silently
2391    /// inert. Emitted once per generation run.
2392    #[non_exhaustive]
2393    DenyUnknownJsonFieldsRequiresJson,
2394    /// [`json_policy_types`](CodeGenConfig::json_policy_types) is non-empty but
2395    /// JSON generation is off, so no field uses a policy.
2396    #[non_exhaustive]
2397    JsonPolicyTypesRequireJson,
2398    /// `idiomatic_field_names` found two or more members of one message whose
2399    /// snake_case conversions collide, and adjusted the affected Rust names
2400    /// deterministically (`_f<number>` suffix for fields, verbatim fallback
2401    /// for oneofs — see [`CodeGenConfig::idiomatic_field_names`]). Wire,
2402    /// JSON, and text-format names are unaffected.
2403    #[non_exhaustive]
2404    IdiomaticFieldNamesAdjusted {
2405        /// Fully-qualified proto name of the affected message.
2406        message_name: String,
2407        /// `(proto_name, final_rust_name)` for each adjusted member, sorted
2408        /// by proto name.
2409        assignments: Vec<(String, String)>,
2410    },
2411    /// A member's keyword-escaped Rust name is also the name of another
2412    /// member, and the keyword member was renamed.
2413    ///
2414    /// A field or oneof whose Rust name is `self`, `super`, `crate` or `Self`
2415    /// (after any `idiomatic_field_names` conversion) is generated as `self_`.
2416    /// Next to a member named `self_`, it is generated as `self__`, with more
2417    /// underscores while that name is taken too. Wire, JSON and text-format
2418    /// names are unaffected. Two oneofs named `self` and `self_` fail with
2419    /// [`CodeGenError::OneofEnumNameConflict`] instead.
2420    ///
2421    /// A field is identified by its name and number, and a oneof by its
2422    /// name, across the messages of every generated file. A message that
2423    /// declares the same member gets the same Rust name and this warning,
2424    /// even when it has no `self_` member of its own.
2425    #[non_exhaustive]
2426    KeywordEscapedNamesAdjusted {
2427        /// Fully-qualified proto name of the affected message.
2428        message_name: String,
2429        /// `(proto_name, final_rust_name)` for each adjusted member, sorted by
2430        /// proto name.
2431        assignments: Vec<(String, String)>,
2432    },
2433    /// A field in a kept file references a type from a package that is neither
2434    /// being generated nor covered by an [`extern_path`](CodeGenConfig::extern_paths)
2435    /// mapping. The generated code will emit a dangling type path that fails to
2436    /// compile in the consumer's build with no indication of where the
2437    /// configuration gap is.
2438    ///
2439    /// Fix by either:
2440    /// - Including the referenced package in the generation request (drop the
2441    ///   `exclude_package` plugin directive or the `.exclude_package(…)` call,
2442    ///   or add the missing `.proto` files to the generate set), or
2443    /// - Adding an `extern_path` mapping for the package pointing to the crate
2444    ///   that provides its generated types.
2445    ///
2446    /// Detection is type-granular: a kept file that generates *some* types from a
2447    /// package while another file in the same package is excluded will still
2448    /// produce a warning for references to the excluded file's types.
2449    ///
2450    /// One warning is emitted per unique `(file_name, type_fqn)` pair; other
2451    /// fields in the same file referencing the same type are not reported
2452    /// separately.
2453    #[non_exhaustive]
2454    ExcludedPackageFieldRef {
2455        /// The proto file that contains the referencing field,
2456        /// e.g. `"path/to/service.proto"`.
2457        file_name: String,
2458        /// The message that contains the referencing field, in dotted form
2459        /// (e.g. `"MyMessage"` or `"Outer.Inner"`). Empty when the reference
2460        /// is a file-level extension rather than a message field.
2461        message_name: String,
2462        /// The name of the field that holds the dangling reference.
2463        field_name: String,
2464        /// The proto package that owns the referenced type,
2465        /// e.g. `"buf.validate"`.
2466        ref_package: String,
2467        /// The fully-qualified type name in the descriptor (leading-dot form,
2468        /// matching the key format of [`CodeGenConfig::extern_paths`]),
2469        /// e.g. `".buf.validate.FieldConstraints"`.
2470        type_fqn: String,
2471    },
2472    /// An [`exclude_packages`](CodeGenConfig::exclude_packages) entry matched
2473    /// no proto package in the descriptor set. Usually a typo in the package
2474    /// name or a stale entry left after a proto reorganization — the entry is
2475    /// accepted but changes nothing.
2476    ///
2477    /// Check the spelling against the `package` declarations in your `.proto`
2478    /// files. The match is exact or prefix-on-component-boundary, so
2479    /// `"buf.validate"` covers `buf.validate` and `buf.validate.priv` but not
2480    /// `buf.validatex`.
2481    #[non_exhaustive]
2482    ExcludePackageMatchedNothing {
2483        /// The normalized package entry that matched nothing
2484        /// (leading dot already stripped).
2485        package: String,
2486    },
2487    /// A [`feature_overrides`](CodeGenConfig::feature_overrides) rule matched
2488    /// nothing the override targets in the compiled descriptor set, so it
2489    /// changed nothing. Usually a typo, a missing nested-message segment, or
2490    /// a stale path after a proto rename — the affected paths silently keep
2491    /// their default semantics.
2492    #[non_exhaustive]
2493    FeatureOverrideMatchedNothing {
2494        /// The rule's path as configured (post-normalization).
2495        rule: String,
2496        /// The overridden feature's name (e.g. `"enum_type"`).
2497        feature: &'static str,
2498        /// The override value (e.g. `"OPEN"`).
2499        value: &'static str,
2500    },
2501    /// A [`preserve_unknown_fields_in`](CodeGenConfig::preserve_unknown_fields_in)
2502    /// rule matched no message being generated, so it changed nothing. Usually
2503    /// a typo, a field path instead of a message path, or a rule for a package
2504    /// mapped through `extern_path` — the affected messages silently keep the
2505    /// global [`preserve_unknown_fields`](CodeGenConfig::preserve_unknown_fields)
2506    /// setting, which for a re-enable rule means losing round-trip fidelity.
2507    #[non_exhaustive]
2508    PreserveUnknownFieldsRuleMatchedNothing {
2509        /// The rule's path as configured.
2510        rule: String,
2511    },
2512    /// A [`deny_unknown_json_fields_in`](CodeGenConfig::deny_unknown_json_fields_in)
2513    /// rule matched no message being generated, so it changed nothing. Usually
2514    /// a typo, a field path instead of a message path, or a rule for a package
2515    /// mapped through `extern_path` — the affected messages silently keep the
2516    /// global [`deny_unknown_json_fields`](CodeGenConfig::deny_unknown_json_fields)
2517    /// setting, which for an enabling rule means unknown JSON keys stay silently
2518    /// ignored.
2519    #[non_exhaustive]
2520    DenyUnknownJsonFieldsRuleMatchedNothing {
2521        /// The rule's path as configured.
2522        rule: String,
2523    },
2524    /// A [`skip_debug`](CodeGenConfig::skip_debug) rule matched no generated
2525    /// message and named no generated enum, so it changed nothing. Usually a
2526    /// typo, a field or oneof path instead of a type path (a oneof is covered
2527    /// by its message's rule), or a rule for a package mapped through
2528    /// `extern_path`. Every generated `Debug` impl is still emitted, so a
2529    /// hand-written impl for the intended type fails to compile as a
2530    /// conflicting implementation.
2531    #[non_exhaustive]
2532    SkipDebugRuleMatchedNothing {
2533        /// The rule's path as configured.
2534        rule: String,
2535    },
2536    /// A [`bytes_fields`](CodeGenConfig::bytes_fields),
2537    /// [`string_fields`](CodeGenConfig::string_fields),
2538    /// [`map_fields`](CodeGenConfig::map_fields) or
2539    /// [`repeated_fields`](CodeGenConfig::repeated_fields) rule matched no
2540    /// field of a message generated by this call, so it changed nothing.
2541    ///
2542    /// Usually a typo, a path without its leading dot or its package, a
2543    /// prost-style suffix path such as `"items"`, or a path into a map-entry
2544    /// message (a rule reaches a map through the map field's own path). A
2545    /// package rule over messages that have no fields also warns.
2546    ///
2547    /// The check compares paths only: a rule whose path is a field of another
2548    /// type (a `string_fields` rule on an `int32` field) is also inert and
2549    /// does not warn. It runs once per `generate` call, so a config shared by
2550    /// several calls warns in each call whose files lack the field.
2551    #[non_exhaustive]
2552    FieldTypeRuleMatchedNothing {
2553        /// The rule's path as it is in the [`CodeGenConfig`] list
2554        /// (`buffa-build` has normalized it).
2555        rule: String,
2556        /// The [`CodeGenConfig`] list that contains the rule: `"bytes_fields"`,
2557        /// `"string_fields"`, `"map_fields"` or `"repeated_fields"`.
2558        option: &'static str,
2559        /// Whether the rule matches a field of a message that this call does
2560        /// not generate: one in an imported file, or in a package under
2561        /// `extern_path` or `exclude_packages`. The `Display` text then says
2562        /// so, in place of the path hint.
2563        matches_ungenerated: bool,
2564    },
2565    /// A [`codec_strategy_in`](CodeGenConfig::codec_strategy_in) rule matched no
2566    /// message being generated, so it changed nothing. Usually a typo, a field
2567    /// path instead of a message path, or a rule for a package mapped through
2568    /// `extern_path`.
2569    #[non_exhaustive]
2570    CodecStrategyRuleMatchedNothing {
2571        /// The rule's path as configured.
2572        rule: String,
2573    },
2574    /// Some messages selected for [`CodecStrategy::Table`], by the global
2575    /// [`codec_strategy`](CodeGenConfig::codec_strategy) or by a
2576    /// [`codec_strategy_in`](CodeGenConfig::codec_strategy_in) rule, cannot use
2577    /// the table and are generated [`CodecStrategy::Unrolled`]. One warning
2578    /// covers the whole run.
2579    #[non_exhaustive]
2580    TableCodecFallbackSummary {
2581        /// The number of messages that fell back.
2582        fallbacks: usize,
2583        /// The number of messages selected for the table.
2584        selected: usize,
2585        /// Why they fell back, most common reason first.
2586        reasons: Vec<TableCodecFallbackReason>,
2587    },
2588}
2589
2590/// The `buffa-build` methods that add to the field-type rule list `option`,
2591/// for [`CodeGenWarning::FieldTypeRuleMatchedNothing`]'s text. A user of
2592/// `buffa-build` typed one of these, not the [`CodeGenConfig`] field's name.
2593fn field_type_rule_builders(option: &str) -> &'static str {
2594    match option {
2595        "bytes_fields" => "bytes_type_in / use_bytes_type_in / bytes_type_custom_in",
2596        "string_fields" => "string_type_in / string_type_custom_in",
2597        "map_fields" => "map_type_in / map_type_custom_in",
2598        "repeated_fields" => "repeated_type_in / repeated_type_custom_in",
2599        _ => "",
2600    }
2601}
2602
2603impl core::fmt::Display for CodeGenWarning {
2604    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2605        match self {
2606            Self::ViewJsonRulesRequireJsonAndViews => f.write_str(
2607                "deny_view_json requires both generate_json and generate_views; the configured restrictions are inactive"
2608            ),
2609            Self::ZeroizeRuleMatchedNothing { rule } => write!(
2610                f, "zeroize_in rule '{rule}' matches no message in this scoped request; validate the full project with allow_unmatched_message_rules=false"
2611            ),
2612            Self::ViewJsonRuleMatchedNothing { rule } => write!(
2613                f, "deny_view_json rule '{rule}' matches no message in this scoped request; validate the full project with allow_unmatched_message_rules=false"
2614            ),
2615            Self::IdiomaticAliasesSuppressed {
2616                enum_name,
2617                conflicts,
2618                invalid,
2619            } => {
2620                // Name the cause accurately: a collision, an invalid identifier,
2621                // or both.
2622                let cause = match (conflicts.is_empty(), invalid.is_empty()) {
2623                    (false, true) => "naming conflict",
2624                    (true, false) => "invalid identifier",
2625                    _ => "naming conflict / invalid identifier",
2626                };
2627                write!(
2628                    f,
2629                    "enum `{enum_name}`: idiomatic CamelCase aliases suppressed ({cause})"
2630                )?;
2631                let mut parts: Vec<String> = conflicts
2632                    .iter()
2633                    .map(|c| format!("{} → {}", c.proto_values.join(", "), c.camel_target))
2634                    .collect();
2635                parts.extend(invalid.iter().map(|n| format!("{n} → invalid identifier")));
2636                if !parts.is_empty() {
2637                    write!(f, ": {}", parts.join("; "))?;
2638                }
2639                Ok(())
2640            }
2641            Self::OwnedViewAccessorSuppressed {
2642                wrapper_name,
2643                field_name,
2644            } => {
2645                write!(
2646                    f,
2647                    "`{wrapper_name}`: accessor for field `{field_name}` suppressed \
2648                     (collides with a reserved wrapper method); use `.view().{field_name}` instead"
2649                )
2650            }
2651            Self::JsonPolicyTypesRequireJson => {
2652                write!(
2653                    f,
2654                    "json_policy_type requires generate_json (there is no generated \
2655                     JSON to route through a policy) — enable generate_json \
2656                     (buffa-build: `.generate_json(true)`; plugin: `json=true`)"
2657                )
2658            }
2659            Self::DenyUnknownJsonFieldsRequiresJson => {
2660                write!(
2661                    f,
2662                    "deny_unknown_json_fields requires generate_json (there are no \
2663                     generated JSON deserializers to make strict); unknown JSON keys \
2664                     are still ignored — enable generate_json (buffa-build: \
2665                     `.generate_json(true)`; plugin: `json=true`)"
2666                )
2667            }
2668            Self::LazyViewsRequireViews => {
2669                write!(
2670                    f,
2671                    "lazy_views requires generate_views (the lazy family reuses the \
2672                     eager view-oneof enums and sub-view types); no lazy views were \
2673                     generated — enable generate_views (buffa-build: \
2674                     `.generate_views(true)`, the default; plugin: `views=true`)"
2675                )
2676            }
2677            Self::IdiomaticFieldNamesAdjusted {
2678                message_name,
2679                assignments,
2680            } => {
2681                let parts: Vec<String> = assignments
2682                    .iter()
2683                    .map(|(proto, rust)| format!("`{proto}` → `{rust}`"))
2684                    .collect();
2685                write!(
2686                    f,
2687                    "message `{message_name}`: idiomatic snake_case field names collide; \
2688                     adjusted: {} (wire/JSON/text names are unaffected)",
2689                    parts.join(", ")
2690                )
2691            }
2692            Self::KeywordEscapedNamesAdjusted {
2693                message_name,
2694                assignments,
2695            } => {
2696                let parts: Vec<String> = assignments
2697                    .iter()
2698                    .map(|(proto, rust)| format!("`{proto}` → `{rust}`"))
2699                    .collect();
2700                write!(
2701                    f,
2702                    "message `{message_name}`: a member's keyword-escaped Rust name is the \
2703                     name of another member, in this message or in one that declares the \
2704                     same member; adjusted: {} (wire/JSON/text names are unaffected)",
2705                    parts.join(", ")
2706                )
2707            }
2708            Self::ExcludedPackageFieldRef {
2709                file_name,
2710                message_name,
2711                field_name,
2712                ref_package,
2713                type_fqn,
2714            } => {
2715                let location = if message_name.is_empty() {
2716                    format!("{file_name}: {field_name}")
2717                } else {
2718                    format!("{file_name}: {message_name}.{field_name}")
2719                };
2720                write!(
2721                    f,
2722                    "field `{location}` references `{type_fqn}`, which is not being \
2723                     generated and has no extern_path mapping; the generated code will \
2724                     contain a dangling type path — map the type or its package \
2725                     `{ref_package}` to the crate that defines it \
2726                     (buffa-build: `.extern_path(\"{type_fqn}\", \"::your_crate::Type\")` \
2727                     or `.extern_path(\".{ref_package}\", \"::your_crate\")`; \
2728                     plugin: `extern_path={type_fqn}=::your_crate::Type` or \
2729                     `extern_path=.{ref_package}=::your_crate`), or include the \
2730                     defining .proto file in the generate set \
2731                     (buffa-build: `.files(&[…])` or drop `.exclude_package(…)`; \
2732                     plugin: drop `exclude_package=`)"
2733                )
2734            }
2735            Self::ExcludePackageMatchedNothing { package } => {
2736                write!(
2737                    f,
2738                    "exclude_package entry \"{package}\" matched no proto package in the \
2739                     descriptor set — check for a typo or a stale entry \
2740                     (exact match or dotted-prefix: \"buf.validate\" covers \
2741                     buf.validate and buf.validate.priv, not buf.validatex)"
2742                )
2743            }
2744            Self::FeatureOverrideMatchedNothing {
2745                rule,
2746                feature,
2747                value,
2748            } => {
2749                write!(
2750                    f,
2751                    "feature override '{rule}' ({feature} = {value}) matched nothing in \
2752                     the compiled set; the affected paths keep their default semantics — \
2753                     check the path against the fully-qualified proto names"
2754                )
2755            }
2756            Self::PreserveUnknownFieldsRuleMatchedNothing { rule } => {
2757                write!(
2758                    f,
2759                    "preserve_unknown_fields_in rule '{rule}' matched no generated message; \
2760                     those messages keep the global preserve_unknown_fields setting — \
2761                     check the path against the fully-qualified proto message names"
2762                )
2763            }
2764            Self::CodecStrategyRuleMatchedNothing { rule } => {
2765                write!(
2766                    f,
2767                    "codec_strategy_in rule '{rule}' matched no generated message; those \
2768                     messages keep the global codec_strategy setting — check the path \
2769                     against the fully-qualified proto message names"
2770                )
2771            }
2772            Self::TableCodecFallbackSummary {
2773                fallbacks,
2774                selected,
2775                reasons,
2776            } => {
2777                write!(
2778                    f,
2779                    "{fallbacks} of {selected} messages selected for the table codec use the \
2780                     unrolled codec instead"
2781                )?;
2782                for (i, r) in reasons.iter().enumerate() {
2783                    let sep = if i == 0 { ": " } else { "; " };
2784                    let shown = r.messages.len().min(3);
2785                    let examples = r.messages[..shown].join(", ");
2786                    let more = match r.messages.len() - shown {
2787                        0 => String::new(),
2788                        n => format!(", and {n} more"),
2789                    };
2790                    write!(
2791                        f,
2792                        "{sep}{} ({}: {examples}{more})",
2793                        r.reason,
2794                        r.messages.len()
2795                    )?;
2796                }
2797                write!(
2798                    f,
2799                    ". To silence this warning, set the messages that fell back to the unrolled \
2800                     codec (buffa-build: `.codec_strategy_in(CodecStrategy::Unrolled, \
2801                     &[\"<path>\"])`; plugin: `codec_strategy_in=<path>=unrolled`)"
2802                )
2803            }
2804            Self::DenyUnknownJsonFieldsRuleMatchedNothing { rule } => {
2805                write!(
2806                    f,
2807                    "deny_unknown_json_fields_in rule '{rule}' matched no generated message; \
2808                     those messages keep the global deny_unknown_json_fields setting — \
2809                     check the path against the fully-qualified proto message names"
2810                )
2811            }
2812            Self::SkipDebugRuleMatchedNothing { rule } => {
2813                write!(
2814                    f,
2815                    "skip_debug rule '{rule}' matched no generated message or enum, \
2816                     so a hand-written Debug impl will conflict with the generated one — \
2817                     use the fully-qualified proto type name \
2818                     (a oneof is covered by its message's rule)"
2819                )
2820            }
2821            Self::FieldTypeRuleMatchedNothing {
2822                rule,
2823                option,
2824                matches_ungenerated,
2825            } => {
2826                let builders = field_type_rule_builders(option);
2827                write!(f, "{option} rule '{rule}' (buffa-build: {builders}) ")?;
2828                if *matches_ungenerated {
2829                    write!(
2830                        f,
2831                        "matches only fields of messages this run does not generate \
2832                         (an imported file, or a package under extern_path or \
2833                         exclude_package), so it changed nothing here"
2834                    )
2835                } else {
2836                    write!(
2837                        f,
2838                        "matched no field of a generated message, so it changed nothing — \
2839                         a rule is a fully-qualified proto path with its leading dot \
2840                         ('.my.pkg', '.my.pkg.Msg' or '.my.pkg.Msg.field'); a bare name \
2841                         such as 'field' or 'Msg.field' does not match"
2842                    )
2843                }
2844            }
2845        }
2846    }
2847}
2848
2849/// The files named in `files_to_generate`, each with its package as a
2850/// leading-dot proto path (empty for a file without a package).
2851fn generated_files<'a>(
2852    file_descriptors: &'a [FileDescriptorProto],
2853    files_to_generate: &'a [String],
2854) -> impl Iterator<Item = (&'a FileDescriptorProto, String)> {
2855    file_descriptors
2856        .iter()
2857        .filter(move |fd| {
2858            fd.name
2859                .as_deref()
2860                .is_some_and(|n| files_to_generate.iter().any(|g| g == n))
2861        })
2862        .map(|fd| {
2863            let package = fd.package.as_deref().unwrap_or("");
2864            let package_fqn = if package.is_empty() {
2865                String::new()
2866            } else {
2867                format!(".{package}")
2868            };
2869            (fd, package_fqn)
2870        })
2871}
2872
2873/// Whether `rule` (a leading-dot proto path prefix) matches at least one
2874/// message, nested messages included, declared in `files_to_generate`.
2875fn rule_matches_generated_message(
2876    rule: &str,
2877    file_descriptors: &[FileDescriptorProto],
2878    files_to_generate: &[String],
2879) -> bool {
2880    fn any_message_matches(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
2881        messages.iter().any(|m| {
2882            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
2883            context::matches_proto_prefix(rule, &fqn)
2884                || any_message_matches(rule, &fqn, &m.nested_type)
2885        })
2886    }
2887
2888    rule == "."
2889        || generated_files(file_descriptors, files_to_generate)
2890            .any(|(fd, package_fqn)| any_message_matches(rule, &package_fqn, &fd.message_type))
2891}
2892
2893/// Whether `rule` (a leading-dot proto path) is the fully-qualified name of
2894/// an enum, top-level or nested in a message, declared in
2895/// `files_to_generate`.
2896fn rule_names_generated_enum(
2897    rule: &str,
2898    file_descriptors: &[FileDescriptorProto],
2899    files_to_generate: &[String],
2900) -> bool {
2901    fn names_enum(rule: &str, parent_fqn: &str, enums: &[EnumDescriptorProto]) -> bool {
2902        enums
2903            .iter()
2904            .any(|e| format!("{parent_fqn}.{}", e.name.as_deref().unwrap_or("")) == rule)
2905    }
2906    fn names_nested_enum(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
2907        messages.iter().any(|m| {
2908            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
2909            names_enum(rule, &fqn, &m.enum_type) || names_nested_enum(rule, &fqn, &m.nested_type)
2910        })
2911    }
2912
2913    generated_files(file_descriptors, files_to_generate).any(|(fd, package_fqn)| {
2914        names_enum(rule, &package_fqn, &fd.enum_type)
2915            || names_nested_enum(rule, &package_fqn, &fd.message_type)
2916    })
2917}
2918
2919/// Whether `rule` (a leading-dot proto path prefix) matches at least one
2920/// field of a message, nested messages included, declared in the files named
2921/// by `file_names`. The fields of a map-entry message do not count: a rule
2922/// reaches a map through the map field's own path.
2923fn rule_matches_field_in(
2924    rule: &str,
2925    file_descriptors: &[FileDescriptorProto],
2926    file_names: &[String],
2927) -> bool {
2928    fn any_field_matches(rule: &str, parent_fqn: &str, messages: &[DescriptorProto]) -> bool {
2929        messages.iter().any(|m| {
2930            let is_map_entry = m
2931                .options
2932                .as_option()
2933                .and_then(|o| o.map_entry)
2934                .unwrap_or(false);
2935            if is_map_entry {
2936                return false;
2937            }
2938            let fqn = format!("{parent_fqn}.{}", m.name.as_deref().unwrap_or(""));
2939            m.field.iter().any(|f| {
2940                let field_fqn = format!("{fqn}.{}", f.name.as_deref().unwrap_or(""));
2941                context::matches_proto_prefix(rule, &field_fqn)
2942            }) || any_field_matches(rule, &fqn, &m.nested_type)
2943        })
2944    }
2945
2946    rule == "."
2947        || generated_files(file_descriptors, file_names)
2948            .any(|(fd, package_fqn)| any_field_matches(rule, &package_fqn, &fd.message_type))
2949}
2950
2951/// The paths of a field-type rule list such as
2952/// [`CodeGenConfig::string_fields`], in order.
2953fn rule_paths<R>(rules: &[(String, R)]) -> Vec<&String> {
2954    rules.iter().map(|(path, _)| path).collect()
2955}
2956
2957/// A later ancestor rule replaces this rule everywhere, independently of which
2958/// directory a plugin request happens to contain. Narrow overrides do not make
2959/// an earlier package-wide rule inert outside their own prefixes.
2960fn unshadowed_rules<R>(rules: &[(String, R)]) -> impl Iterator<Item = &R> {
2961    rules
2962        .iter()
2963        .enumerate()
2964        .filter_map(|(index, (path, repr))| {
2965            let next = index.checked_add(1)?;
2966            (!rules
2967                .iter()
2968                .skip(next)
2969                .any(|(later, _)| context::matches_proto_prefix(later, path)))
2970            .then_some(repr)
2971        })
2972}
2973
2974/// Generate Rust source files from a set of file descriptors.
2975///
2976/// `files_to_generate` is the set of file names that were explicitly requested
2977/// (matching `CodeGeneratorRequest.file_to_generate`). Descriptors for
2978/// dependencies may be present in `file_descriptors` but won't produce output
2979/// files unless they appear in `files_to_generate`. A name listed twice is
2980/// generated once.
2981///
2982/// Each `.proto` emits up to five content files (kinds with no content
2983/// are omitted); each distinct package emits one `<pkg>.mod.rs`
2984/// stitcher. Packages are processed in sorted order for deterministic
2985/// output.
2986///
2987/// # Diagnostics
2988///
2989/// Non-fatal diagnostics produced during generation (e.g. an enum whose
2990/// idiomatic CamelCase aliases were suppressed by a naming conflict) are
2991/// **discarded** here. Use [`generate_with_diagnostics`] to receive them and
2992/// surface them as build warnings.
2993///
2994/// # Errors
2995///
2996/// As [`generate_with_diagnostics`].
2997pub fn generate(
2998    file_descriptors: &[FileDescriptorProto],
2999    files_to_generate: &[String],
3000    config: &CodeGenConfig,
3001) -> Result<Vec<GeneratedFile>, CodeGenError> {
3002    Ok(generate_with_diagnostics(file_descriptors, files_to_generate, config)?.0)
3003}
3004
3005/// Whether a custom `repeated` element type holds proto `string` or `bytes` —
3006/// selects `ValueRef::String`/`ValueRef::Bytes` and the JSON delegate module.
3007#[derive(Clone, Copy, PartialEq, Eq)]
3008enum CustomElemKind {
3009    String,
3010    Bytes,
3011}
3012
3013/// The custom owned types collected generation-wide that need a codegen-emitted
3014/// reflection / JSON impl, split by the trait each needs.
3015#[derive(Default)]
3016struct CustomElements {
3017    /// Types needing `ReflectElement` (+ `ProtoElemJson` for bytes): custom
3018    /// `repeated` elements, custom `map` *values* (`string` or `bytes`).
3019    elements: std::collections::BTreeMap<String, CustomElemKind>,
3020    /// Custom `string` types used as a `map` *key*: need `ReflectMapKey` (vtable
3021    /// reflection only — the bridge path keys maps by the borrowed `&str` view).
3022    map_keys: std::collections::BTreeSet<String>,
3023}
3024
3025/// Collect the distinct custom owned types that need a codegen-emitted element
3026/// impl (`ReflectElement` / `ProtoElemJson`), keyed by Rust type path, across
3027/// the whole request. These are custom `string`/`bytes` types used as the
3028/// element of a `repeated` field, and custom `bytes` types used as a
3029/// `map<K, bytes>` value — both reflect via the element trait and (for bytes)
3030/// serialize JSON via `proto_map`/`proto_seq`. Singular / optional / oneof
3031/// custom fields reach JSON and reflection without an element-trait impl, and
3032/// `string`/`Vec<u8>`/`Bytes` map values are covered by the built-in impls.
3033fn collect_custom_elements(
3034    ctx: &context::CodeGenContext,
3035    file_descriptors: &[FileDescriptorProto],
3036    files_to_generate: &[String],
3037    all_fields: bool,
3038) -> CustomElements {
3039    use crate::generated::descriptor::field_descriptor_proto::{Label, Type};
3040
3041    fn walk(
3042        ctx: &context::CodeGenContext,
3043        messages: &[crate::generated::descriptor::DescriptorProto],
3044        scope: &str,
3045        parent_features: &crate::features::ResolvedFeatures,
3046        out: &mut CustomElements,
3047        all_fields: bool,
3048    ) {
3049        for msg in messages {
3050            if msg
3051                .options
3052                .as_option()
3053                .and_then(|options| options.map_entry)
3054                .unwrap_or(false)
3055            {
3056                continue;
3057            }
3058            let name = msg.name.as_deref().unwrap_or("");
3059            let fqn = if scope.is_empty() {
3060                name.to_string()
3061            } else {
3062                format!("{scope}.{name}")
3063            };
3064            let msg_features = crate::features::resolve_child(
3065                parent_features,
3066                crate::features::message_features(msg),
3067            );
3068            for field in &msg.field {
3069                if !all_fields && field.label.unwrap_or_default() != Label::LABEL_REPEATED {
3070                    continue;
3071                }
3072                let field_name = field.name.as_deref().unwrap_or("");
3073                let field_fqn = format!(".{fqn}.{field_name}");
3074
3075                // `map` slots: a custom value type needs the element impls
3076                // (reflected via ReflectMap → ReflectElement, JSON via
3077                // proto_map → ProtoElemJson for bytes), and a custom `string`
3078                // key needs ReflectMapKey. All keyed on the outer map field
3079                // path (the same `string_type` rule covers both slots), with the
3080                // `map<bytes, bytes>` value carve-out.
3081                if let Some(entry) = crate::message::find_map_entry(msg, field) {
3082                    let key_ty = crate::message::map_entry_key_type(ctx, entry, &msg_features);
3083                    let val_ty = crate::message::map_entry_value_type(ctx, entry, &msg_features);
3084                    if let crate::BytesRepr::Custom(path) =
3085                        crate::impl_message::map_value_bytes_repr(
3086                            ctx, key_ty, val_ty, &fqn, field_name,
3087                        )
3088                    {
3089                        out.elements
3090                            .entry(context::rust_type_key(&path))
3091                            .or_insert(CustomElemKind::Bytes);
3092                    }
3093                    if let crate::StringRepr::Custom(path) = ctx.string_repr(&field_fqn) {
3094                        if key_ty == Some(Type::TYPE_STRING) {
3095                            out.map_keys.insert(context::rust_type_key(&path));
3096                        }
3097                        if val_ty == Some(Type::TYPE_STRING) {
3098                            out.elements
3099                                .entry(context::rust_type_key(&path))
3100                                .or_insert(CustomElemKind::String);
3101                        }
3102                    }
3103                    continue;
3104                }
3105
3106                let field_features = crate::features::resolve_field(ctx, field, &msg_features);
3107                let ty = crate::impl_message::effective_type(ctx, field, &field_features);
3108                match ty {
3109                    Type::TYPE_STRING => {
3110                        if let crate::StringRepr::Custom(path) = ctx.string_repr(&field_fqn) {
3111                            out.elements
3112                                .entry(context::rust_type_key(&path))
3113                                .or_insert(CustomElemKind::String);
3114                        }
3115                    }
3116                    Type::TYPE_BYTES => {
3117                        if let crate::BytesRepr::Custom(path) = ctx.bytes_repr(&field_fqn) {
3118                            out.elements
3119                                .entry(context::rust_type_key(&path))
3120                                .or_insert(CustomElemKind::Bytes);
3121                        }
3122                    }
3123                    _ => {}
3124                }
3125            }
3126            walk(ctx, &msg.nested_type, &fqn, &msg_features, out, all_fields);
3127        }
3128    }
3129
3130    let mut out = CustomElements::default();
3131    for file_name in files_to_generate {
3132        let Some(file) = file_descriptors
3133            .iter()
3134            .find(|f| f.name.as_deref() == Some(file_name.as_str()))
3135        else {
3136            continue;
3137        };
3138        let pkg = file.package.as_deref().unwrap_or("");
3139        let file_features = crate::features::for_file(file);
3140        walk(
3141            ctx,
3142            &file.message_type,
3143            pkg,
3144            &file_features,
3145            &mut out,
3146            all_fields,
3147        );
3148    }
3149    out
3150}
3151
3152/// Render the deduped `ProtoElemJson` / `ReflectElement` impls for the collected
3153/// custom element types (repeated elements and `map<K, bytes>` values). Each
3154/// impl is feature-gated so a non-JSON /
3155/// non-reflect build never references an absent trait. These compile only when
3156/// the custom type is local to the generating crate (the orphan rule); that is
3157/// the documented limitation of a custom `repeated` element under JSON or vtable
3158/// reflection.
3159fn render_custom_elem_impls(
3160    ctx: &context::CodeGenContext,
3161    elems: &CustomElements,
3162) -> Result<TokenStream, CodeGenError> {
3163    if !ctx.config.emit_custom_type_impls {
3164        return Ok(TokenStream::new());
3165    }
3166    let json_gate = ctx.config.feature_gates().json;
3167    let reflect_gate = ctx.config.feature_gates().reflect;
3168    let mut out = TokenStream::new();
3169    for (path, kind) in &elems.elements {
3170        let ty = parse_custom_type_path(path)?;
3171        // A JSON policy type's elements always go through its policy trait,
3172        // whether it is a `bytes` or a `string` representation: codegen routes
3173        // its repeated fields and map values through `ProtoElemJson`.
3174        if ctx.is_json_policy_type(path) {
3175            let policy = match kind {
3176                CustomElemKind::Bytes => quote! { ::buffa::json_helpers::ProtoBytesJson },
3177                CustomElemKind::String => quote! { ::buffa::json_helpers::ProtoStringJson },
3178            };
3179            let borrowed = match kind {
3180                CustomElemKind::Bytes => quote! { [u8] },
3181                CustomElemKind::String => quote! { str },
3182            };
3183            out.extend(feature_gates::cfg_block(
3184                quote! {
3185                    impl ::buffa::json_helpers::ProtoElemJson for #ty {
3186                        fn serialize_proto_json<__S: ::serde::Serializer>(
3187                            v: &Self,
3188                            s: __S,
3189                        ) -> ::core::result::Result<__S::Ok, __S::Error> {
3190                            <Self as #policy>::serialize_json(
3191                                ::core::convert::AsRef::<#borrowed>::as_ref(v),
3192                                s,
3193                            )
3194                        }
3195                        fn deserialize_proto_json<'de, __D: ::serde::Deserializer<'de>>(
3196                            d: __D,
3197                        ) -> ::core::result::Result<Self, __D::Error> {
3198                            <Self as #policy>::deserialize_json(d)
3199                        }
3200                    }
3201                },
3202                json_gate,
3203            ));
3204        }
3205        // Otherwise `ProtoElemJson` is only needed for the `bytes` element
3206        // path (proto3 JSON base64). A repeated `string` element serializes
3207        // through the native `Vec<T>` serde derive, and custom `string` map
3208        // keys/values go through serde too (the derive / `string_key_map` /
3209        // `proto_str_key_map` paths), so a String-kind `ProtoElemJson` impl
3210        // would be dead code.
3211        else if ctx.config.generate_json && *kind == CustomElemKind::Bytes {
3212            out.extend(feature_gates::cfg_block(
3213                quote! {
3214                    impl ::buffa::json_helpers::ProtoElemJson for #ty {
3215                        fn serialize_proto_json<__S: ::serde::Serializer>(
3216                            v: &Self,
3217                            s: __S,
3218                        ) -> ::core::result::Result<__S::Ok, __S::Error> {
3219                            ::buffa::json_helpers::bytes::serialize(
3220                                ::core::convert::AsRef::<[u8]>::as_ref(v),
3221                                s,
3222                            )
3223                        }
3224                        fn deserialize_proto_json<'de, __D: ::serde::Deserializer<'de>>(
3225                            d: __D,
3226                        ) -> ::core::result::Result<Self, __D::Error> {
3227                            ::buffa::json_helpers::bytes::deserialize(d)
3228                        }
3229                    }
3230                },
3231                json_gate,
3232            ));
3233        }
3234        if ctx.config.generate_reflection_vtable {
3235            let value_ref = match kind {
3236                CustomElemKind::String => quote! {
3237                    ::buffa_descriptor::reflect::ValueRef::String(
3238                        ::core::convert::AsRef::<str>::as_ref(self),
3239                    )
3240                },
3241                CustomElemKind::Bytes => quote! {
3242                    ::buffa_descriptor::reflect::ValueRef::Bytes(
3243                        ::core::convert::AsRef::<[u8]>::as_ref(self),
3244                    )
3245                },
3246            };
3247            out.extend(feature_gates::cfg_block(
3248                quote! {
3249                    impl ::buffa_descriptor::reflect::ReflectElement for #ty {
3250                        fn as_value_ref(&self) -> ::buffa_descriptor::reflect::ValueRef<'_> {
3251                            #value_ref
3252                        }
3253                    }
3254                },
3255                reflect_gate,
3256            ));
3257        }
3258        if ctx.config.generate_reflection
3259            && (ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty())
3260        {
3261            let value = match kind {
3262                CustomElemKind::String => quote! {
3263                    ::buffa_descriptor::reflect::InspectValueRef::String(self.as_ref())
3264                },
3265                CustomElemKind::Bytes => quote! {
3266                    ::buffa_descriptor::reflect::InspectValueRef::Bytes(self.as_ref())
3267                },
3268            };
3269            out.extend(feature_gates::cfg_block(
3270                quote! {
3271                    impl ::buffa_descriptor::reflect::InspectElement for #ty {
3272                        fn as_inspect_value(&self) -> ::buffa_descriptor::reflect::InspectValueRef<'_> {
3273                            #value
3274                        }
3275                    }
3276                },
3277                reflect_gate,
3278            ));
3279        }
3280    }
3281    // A custom `string` type used as a `map` key needs `ReflectMapKey` for
3282    // vtable reflection (the bridge path keys maps by the borrowed `&str` view,
3283    // which already implements it). Like the element impls above, this compiles
3284    // only when the type is local to the generating crate (the orphan rule).
3285    if ctx.config.generate_reflection_vtable
3286        || (ctx.config.generate_reflection
3287            && (ctx.config.generate_zeroize || !ctx.config.zeroize_messages.is_empty()))
3288    {
3289        for path in &elems.map_keys {
3290            let ty = parse_custom_type_path(path)?;
3291            out.extend(feature_gates::cfg_block(
3292                quote! {
3293                    impl ::buffa_descriptor::reflect::ReflectMapKey for #ty {
3294                        fn as_map_key_ref(&self) -> ::buffa_descriptor::reflect::MapKeyRef<'_> {
3295                            ::buffa_descriptor::reflect::MapKeyRef::String(
3296                                ::core::convert::AsRef::<str>::as_ref(self),
3297                            )
3298                        }
3299                    }
3300                },
3301                reflect_gate,
3302            ));
3303        }
3304    }
3305    Ok(out)
3306}
3307
3308// ── Excluded-package field-reference detection ───────────────────────────
3309
3310/// Invariants shared across the recursive field-reference walk.
3311#[derive(Clone, Copy)]
3312struct ExcludedRefScan<'a> {
3313    ctx: &'a context::CodeGenContext<'a>,
3314    /// Effective package-level and per-type extern paths (from
3315    /// [`effective_extern_paths`], including the auto-injected WKT mapping).
3316    extern_paths: &'a [(String, String)],
3317    /// FQNs declared in the kept files — these are always safe to reference.
3318    declared_in_kept: &'a std::collections::HashSet<String>,
3319    /// FQNs covered by file-level extern paths (e.g. `descriptor.proto` →
3320    /// `::buffa_descriptor`). These resolve externally even when the
3321    /// package-level `extern_paths` don't cover them.
3322    file_extern_covered: &'a std::collections::HashSet<String>,
3323}
3324
3325/// Populate `out` with all message/enum FQNs declared in `file` (in
3326/// leading-dot form, e.g. `.my.pkg.MyMessage`).
3327fn collect_fqns_in_file(file: &FileDescriptorProto, out: &mut std::collections::HashSet<String>) {
3328    let pkg = file.package.as_deref().unwrap_or("");
3329    for msg in &file.message_type {
3330        let Some(name) = &msg.name else { continue };
3331        let fqn = if pkg.is_empty() {
3332            format!(".{name}")
3333        } else {
3334            format!(".{pkg}.{name}")
3335        };
3336        collect_fqns_msg_recursive(&fqn, msg, out);
3337    }
3338    for en in &file.enum_type {
3339        let Some(name) = &en.name else { continue };
3340        let fqn = if pkg.is_empty() {
3341            format!(".{name}")
3342        } else {
3343            format!(".{pkg}.{name}")
3344        };
3345        out.insert(fqn);
3346    }
3347}
3348
3349fn collect_fqns_msg_recursive(
3350    msg_fqn: &str,
3351    msg: &crate::generated::descriptor::DescriptorProto,
3352    out: &mut std::collections::HashSet<String>,
3353) {
3354    out.insert(msg_fqn.to_string());
3355    for nested in &msg.nested_type {
3356        let Some(name) = &nested.name else { continue };
3357        let nested_fqn = format!("{msg_fqn}.{name}");
3358        collect_fqns_msg_recursive(&nested_fqn, nested, out);
3359    }
3360    for en in &msg.enum_type {
3361        let Some(name) = &en.name else { continue };
3362        out.insert(format!("{msg_fqn}.{name}"));
3363    }
3364}
3365
3366/// Check whether `type_fqn` is resolvable and, if not, emit an
3367/// `ExcludedPackageFieldRef` warning.
3368///
3369/// `field_name` is the *attribution* name used in the warning — normally the
3370/// proto field name, but for map fields it is the outer map field name (e.g.
3371/// `"prices"`) rather than the synthetic entry's `"value"` slot.
3372fn warn_excluded_refs_type(
3373    scan: ExcludedRefScan<'_>,
3374    file_name: &str,
3375    message_name: &str,
3376    field_name: &str,
3377    type_fqn: &str,
3378    warned: &mut std::collections::HashSet<(String, String)>,
3379) {
3380    // Types declared in kept files are always resolvable.
3381    if scan.declared_in_kept.contains(type_fqn) {
3382        return;
3383    }
3384
3385    // Look up the package for the diagnostic; if the type is absent from the
3386    // descriptor set, codegen raises a hard error — skip quietly.
3387    let Some(ref_package) = scan.ctx.package_of(type_fqn) else {
3388        return;
3389    };
3390
3391    // Package-less (.proto) types: the fix guidance would suggest `.` as an
3392    // extern_path key, which acts as a catch-all — skip to avoid misleading advice.
3393    if ref_package.is_empty() {
3394        return;
3395    }
3396
3397    // A per-type or package-level extern_path suppresses the warning.
3398    if context::resolve_extern_type(type_fqn, scan.extern_paths).is_some() {
3399        return;
3400    }
3401
3402    // File-level externs (e.g. `descriptor.proto` → `::buffa_descriptor`)
3403    // also suppress — they resolve externally even when no package mapping exists.
3404    if scan.file_extern_covered.contains(type_fqn) {
3405        return;
3406    }
3407
3408    // Deduplicate by (file, type_fqn): one warning per unique referenced type per file.
3409    if !warned.insert((file_name.to_string(), type_fqn.to_string())) {
3410        return;
3411    }
3412
3413    scan.ctx.warn(CodeGenWarning::ExcludedPackageFieldRef {
3414        file_name: file_name.to_string(),
3415        message_name: message_name.to_string(),
3416        field_name: field_name.to_string(),
3417        ref_package: ref_package.to_string(),
3418        type_fqn: type_fqn.to_string(),
3419    });
3420}
3421
3422fn warn_excluded_refs_field(
3423    scan: ExcludedRefScan<'_>,
3424    file_name: &str,
3425    field: &crate::generated::descriptor::FieldDescriptorProto,
3426    message_name: &str,
3427    warned: &mut std::collections::HashSet<(String, String)>,
3428) {
3429    let Some(type_fqn) = field.type_name.as_deref().filter(|s| !s.is_empty()) else {
3430        return;
3431    };
3432    warn_excluded_refs_type(
3433        scan,
3434        file_name,
3435        message_name,
3436        field.name.as_deref().unwrap_or("?"),
3437        type_fqn,
3438        warned,
3439    );
3440}
3441
3442fn warn_excluded_refs_msg(
3443    scan: ExcludedRefScan<'_>,
3444    file_name: &str,
3445    msg: &crate::generated::descriptor::DescriptorProto,
3446    parent_path: &str,
3447    warned: &mut std::collections::HashSet<(String, String)>,
3448) {
3449    let msg_name = msg.name.as_deref().unwrap_or("?");
3450    let message_path = if parent_path.is_empty() {
3451        msg_name.to_string()
3452    } else {
3453        format!("{parent_path}.{msg_name}")
3454    };
3455    use crate::generated::descriptor::field_descriptor_proto::Label;
3456    for field in &msg.field {
3457        // Always check the field itself: for plain message fields this emits a
3458        // warning when the type is excluded; for genuine map fields, type_name
3459        // points at the synthetic entry (same file, in declared_in_kept), so
3460        // warn_excluded_refs_type returns immediately with no warning.
3461        warn_excluded_refs_field(scan, file_name, field, &message_path, warned);
3462
3463        // Additionally, for map fields, look through the synthetic entry to the
3464        // value field: the entry is safe (declared_in_kept), but the value type
3465        // may be from an excluded package. Attribute the warning to the outer
3466        // map field name (e.g. "prices"), not the entry's "value" slot.
3467        //
3468        // The LABEL_REPEATED gate mirrors every other is_map_field call site:
3469        // is_map_field looks at the type, not the label, so a singular field
3470        // typed as the synthetic entry would otherwise get the value-slot
3471        // check. The field itself is already checked above either way.
3472        let is_repeated = field.label.unwrap_or_default() == Label::LABEL_REPEATED;
3473        if is_repeated && crate::message::is_map_field(msg, field) {
3474            // Malformed entries (no key/value) are silently skipped — this is a
3475            // diagnostic pass; real codegen errors on the same descriptor follow.
3476            if let Ok((_, value_field)) = crate::impl_message::find_map_entry_fields(msg, field) {
3477                if let Some(type_fqn) = value_field.type_name.as_deref().filter(|s| !s.is_empty()) {
3478                    warn_excluded_refs_type(
3479                        scan,
3480                        file_name,
3481                        &message_path,
3482                        field.name.as_deref().unwrap_or("?"),
3483                        type_fqn,
3484                        warned,
3485                    );
3486                }
3487            }
3488        }
3489    }
3490    for ext in &msg.extension {
3491        warn_excluded_refs_field(scan, file_name, ext, &message_path, warned);
3492    }
3493    for nested in &msg.nested_type {
3494        // Skip synthetic map-entry messages: their cross-package references are
3495        // checked above via the owning map field.
3496        if nested
3497            .options
3498            .as_option()
3499            .and_then(|o| o.map_entry)
3500            .unwrap_or(false)
3501        {
3502            continue;
3503        }
3504        warn_excluded_refs_msg(scan, file_name, nested, &message_path, warned);
3505    }
3506}
3507
3508/// Like [`generate`], but also returns the non-fatal [`CodeGenWarning`]s
3509/// collected during generation (e.g. enums whose idiomatic CamelCase aliases
3510/// were suppressed by a naming conflict).
3511///
3512/// Report each warning through its [`Display`](core::fmt::Display) impl — e.g.
3513/// as a `cargo:warning=...` from a `build.rs`, or on stderr from a standalone
3514/// generator — or match on it for programmatic handling. [`generate`] discards
3515/// them.
3516///
3517/// A name listed twice in `files_to_generate` is generated once.
3518///
3519/// Warnings are returned only on success. On error, any warnings already
3520/// collected are dropped along with the partial output — the [`CodeGenError`]
3521/// is the actionable signal.
3522///
3523/// # Errors
3524///
3525/// - [`CodeGenError::FileNotFound`] if a name in `files_to_generate` has no
3526///   matching descriptor.
3527/// - [`CodeGenError::OutputFileNameConflict`] if two generated files would
3528///   be written to the same output path.
3529/// - [`CodeGenError::InvalidTypeNamePrefix`] if
3530///   [`CodeGenConfig::type_name_prefix`] is neither empty nor PascalCase.
3531/// - [`CodeGenError::InvalidCustomAttribute`] if a custom attribute string,
3532///   such as one in [`CodeGenConfig::type_attributes`], is not one or more
3533///   outer `#[...]` attributes.
3534/// - [`CodeGenError::Other`] if `config` sets an option without the option
3535///   it requires: `generate_reflection_vtable` or `shared_descriptor_pool`
3536///   without `generate_reflection`, `shared_descriptor_pool_root` without
3537///   `shared_descriptor_pool`, or `idiomatic_imports` without
3538///   `file_per_package`.
3539/// - [`CodeGenError::Other`] if an active feature-gate name in
3540///   [`CodeGenConfig::feature_gate_names`] is not a valid Cargo feature name,
3541///   or if `shared_descriptor_pool_root` or an `exclude_packages` entry is
3542///   malformed.
3543/// - [`CodeGenError::SharedCorpusContextMismatch`] if
3544///   [`CodeGenConfig::shared_corpus_context`] was built from a different
3545///   corpus or different rules than this call uses.
3546/// - For a valid schema whose names collide in the generated Rust:
3547///   [`CodeGenError::OneofEnumNameConflict`],
3548///   [`CodeGenError::OneofVariantNameConflict`],
3549///   [`CodeGenError::TypeNameConflict`],
3550///   [`CodeGenError::ModuleNameConflict`],
3551///   [`CodeGenError::ReservedFieldName`] or
3552///   [`CodeGenError::ReservedModuleName`].
3553/// - [`CodeGenError::DuplicateFieldNumber`] if a message of a file in
3554///   `files_to_generate` has two fields with one field number, which protoc
3555///   rejects.
3556/// - Other [`CodeGenError`] variants for a schema that generation does not
3557///   support or a malformed descriptor, such as
3558///   [`CodeGenError::MissingField`].
3559pub fn generate_with_diagnostics(
3560    file_descriptors: &[FileDescriptorProto],
3561    files_to_generate: &[String],
3562    config: &CodeGenConfig,
3563) -> Result<(Vec<GeneratedFile>, Vec<CodeGenWarning>), CodeGenError> {
3564    // Vtable reflection resolves against the per-package descriptor pool, which
3565    // is emitted by bridge-mode reflection — so it requires `generate_reflection`.
3566    // It does NOT require views: the owned `impl ReflectMessage` is self-contained,
3567    // so with views off, vtable mode still emits owned-message reflection (the
3568    // view impls are simply skipped along with the views).
3569    if config.generate_reflection_vtable && !config.generate_reflection {
3570        return Err(CodeGenError::Other(
3571            "generate_reflection_vtable requires generate_reflection to be enabled \
3572             (it provides the descriptor pool the reflect impls resolve against)"
3573                .into(),
3574        ));
3575    }
3576
3577    // Shared-pool mode only rearranges where the reflection descriptor bytes
3578    // live, so it is meaningless — and would silently no-op — without
3579    // reflection. Reject it up front rather than dropping the flag.
3580    if config.shared_descriptor_pool && !config.generate_reflection {
3581        return Err(CodeGenError::Other(
3582            "shared_descriptor_pool requires generate_reflection to be enabled \
3583             (it deduplicates the embedded reflection descriptor pool)"
3584                .into(),
3585        ));
3586    }
3587
3588    // shared_descriptor_pool_root only overrides how the shared root is
3589    // reached, so — like shared_descriptor_pool without generate_reflection
3590    // above — it is meaningless, and would silently no-op, without
3591    // shared_descriptor_pool itself. Reject it up front rather than
3592    // dropping the override.
3593    if let Some(root) = &config.shared_descriptor_pool_root {
3594        if !config.shared_descriptor_pool {
3595            return Err(CodeGenError::Other(
3596                "shared_descriptor_pool_root requires shared_descriptor_pool to be \
3597                 enabled (it overrides the path to the shared root, which only exists \
3598                 in shared-pool mode)"
3599                    .into(),
3600            ));
3601        }
3602        validate_shared_root_path(root)?;
3603    }
3604
3605    // Idiomatic imports place `use` directives in the package-root scope,
3606    // which is only single-writer (collision-free by construction) when the
3607    // whole package is one generated file.
3608    if config.idiomatic_imports && !config.file_per_package {
3609        return Err(CodeGenError::Other(
3610            "idiomatic_imports requires file_per_package to be enabled (the multi-file \
3611             layout include!-merges every proto's content into the shared package root, \
3612             where emitted `use` directives could collide across files)"
3613                .into(),
3614        ));
3615    }
3616
3617    // Active feature-gate names are emitted verbatim into
3618    // `#[cfg(feature = "...")]`; an invalid name fails open (the cfg is
3619    // permanently false and the gated impls silently compile away), so it
3620    // must be a hard error here rather than a debug assertion — build
3621    // scripts and protoc plugins typically run as release builds.
3622    if let Err((kind, name)) = config.feature_gates().validate() {
3623        return Err(CodeGenError::Other(format!(
3624            "invalid {kind} feature-gate name {name:?}: a Cargo feature name starts \
3625             with an ASCII alphanumeric or '_' and contains only alphanumerics, \
3626             '_', '-', '+', or '.'; an invalid name would leave the emitted \
3627             #[cfg(feature = ...)] permanently false, silently compiling the \
3628             gated impls away"
3629        )));
3630    }
3631
3632    config.validate_type_name_prefix()?;
3633    context::validate_custom_attributes(config)?;
3634
3635    // Normalize exclude_packages entries (optional leading dot stripped). The
3636    // plugin normalizes before it gets here and buffa-build validates in
3637    // `compile()`, so this is the one place a direct `CodeGenConfig` caller's
3638    // entries are checked; the message is the normalizer's own.
3639    let normalized_excludes: Vec<String> = config
3640        .exclude_packages
3641        .iter()
3642        .map(|entry| {
3643            normalize_exclude_package(entry)
3644                .map_err(|e| CodeGenError::Other(format!("exclude_package {entry:?}: {e}")))
3645        })
3646        .collect::<Result<_, _>>()?;
3647    // Drop files whose proto package is listed in `config.exclude_packages`
3648    // BEFORE building the codegen context, so that context decisions that key
3649    // on `files_to_generate` membership (e.g. WKT auto-extern-path injection,
3650    // descriptor.proto suppression) see the filtered set. Their descriptors
3651    // stay in `file_descriptors` for type resolution; only code generation is
3652    // skipped. A file with no matching descriptor is kept — the FileNotFound
3653    // error below is more actionable than silently dropping it here.
3654    let effective_files_to_generate: std::borrow::Cow<'_, [String]> =
3655        if normalized_excludes.is_empty() {
3656            std::borrow::Cow::Borrowed(files_to_generate)
3657        } else {
3658            std::borrow::Cow::Owned(
3659                files_to_generate
3660                    .iter()
3661                    .filter(|name| {
3662                        match file_descriptors
3663                            .iter()
3664                            .find(|fd| fd.name.as_deref() == Some(name.as_str()))
3665                        {
3666                            Some(fd) => !package_is_excluded(
3667                                fd.package.as_deref().unwrap_or(""),
3668                                &normalized_excludes,
3669                            ),
3670                            None => true,
3671                        }
3672                    })
3673                    .cloned()
3674                    .collect(),
3675            )
3676        };
3677    let files_to_generate: &[String] = &effective_files_to_generate;
3678
3679    // Feature overrides are applied by mutating the descriptor set up front,
3680    // so every downstream consumer — feature resolution, all generation
3681    // paths, and the embedded reflection descriptor pool — reads the same
3682    // overridden features. With no overrides configured this is a no-op
3683    // borrow.
3684    let overridden =
3685        feature_overrides::apply_feature_overrides(file_descriptors, &config.feature_overrides);
3686    let file_descriptors: &[FileDescriptorProto] =
3687        overridden.as_ref().map_or(file_descriptors, |o| &o.files);
3688
3689    if let Some(shared) = &config.shared_corpus_context {
3690        shared.check(file_descriptors, config)?;
3691    }
3692    let ctx = context::CodeGenContext::for_generate(file_descriptors, files_to_generate, config);
3693
3694    // An inert rule means the user opted a path out of its default semantics
3695    // and silently didn't get it — warn per rule so typos surface at build
3696    // time instead of as production behavior surprises.
3697    if let Some(o) = &overridden {
3698        for (rule, ovr) in &o.unmatched {
3699            ctx.warn(CodeGenWarning::FeatureOverrideMatchedNothing {
3700                rule: rule.clone(),
3701                feature: ovr.feature_name(),
3702                value: ovr.value_name(),
3703            });
3704        }
3705    }
3706
3707    // A `preserve_unknown_fields_in` rule that names no generated message
3708    // (typo, field path, extern-mapped package) leaves its intended messages
3709    // on the global default — for a re-enable rule, silently losing
3710    // round-trip fidelity — so warn per rule.
3711    for (rule, _) in &config.preserve_unknown_fields_in {
3712        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
3713            ctx.warn(CodeGenWarning::PreserveUnknownFieldsRuleMatchedNothing {
3714                rule: rule.clone(),
3715            });
3716        }
3717    }
3718
3719    let known_files = file_descriptors
3720        .iter()
3721        .filter_map(|file| file.name.clone())
3722        .collect::<Vec<_>>();
3723    for rule in &config.zeroize_messages {
3724        if rule.trim().is_empty() {
3725            return Err(CodeGenError::ZeroizeRuleMatchedNothing { rule: rule.clone() });
3726        }
3727        if !rule_matches_generated_message(rule, file_descriptors, &known_files) {
3728            if config.allow_unmatched_message_rules {
3729                ctx.warn(CodeGenWarning::ZeroizeRuleMatchedNothing { rule: rule.clone() });
3730            } else {
3731                return Err(CodeGenError::ZeroizeRuleMatchedNothing { rule: rule.clone() });
3732            }
3733        }
3734    }
3735    for rule in &config.deny_view_json {
3736        if rule.trim().is_empty() {
3737            return Err(CodeGenError::ViewJsonRuleMatchedNothing { rule: rule.clone() });
3738        }
3739        if !rule_matches_generated_message(rule, file_descriptors, &known_files) {
3740            if config.allow_unmatched_message_rules {
3741                ctx.warn(CodeGenWarning::ViewJsonRuleMatchedNothing { rule: rule.clone() });
3742            } else {
3743                return Err(CodeGenError::ViewJsonRuleMatchedNothing { rule: rule.clone() });
3744            }
3745        }
3746    }
3747
3748    if !config.deny_view_json.is_empty() && (!config.generate_json || !config.generate_views) {
3749        ctx.warn(CodeGenWarning::ViewJsonRulesRequireJsonAndViews);
3750    }
3751
3752    // A JSON policy needs generated JSON, and a listed type must be one that a
3753    // representation rule actually selects.
3754    if !config.json_policy_types.is_empty() && !config.generate_json {
3755        ctx.warn(CodeGenWarning::JsonPolicyTypesRequireJson);
3756    }
3757    // Validate configuration bindings, not just fields in this invocation.
3758    // Buf's directory strategy gives each process only that directory's files;
3759    // policy types used by another directory must still be accepted here.
3760    let representation_types = unshadowed_rules(&config.bytes_fields)
3761        .filter_map(|repr| match repr {
3762            BytesRepr::Custom(path) => Some(path),
3763            _ => None,
3764        })
3765        .chain(
3766            unshadowed_rules(&config.string_fields).filter_map(|repr| match repr {
3767                StringRepr::Custom(path) => Some(path),
3768                _ => None,
3769            }),
3770        )
3771        .collect::<Vec<_>>();
3772    for rust_type in &config.json_policy_types {
3773        let key = context::rust_type_key(rust_type);
3774        let selected = representation_types
3775            .iter()
3776            .any(|path| context::rust_type_key(path) == key);
3777        if !selected {
3778            return Err(CodeGenError::JsonPolicyTypeMatchedNothing {
3779                rust_type: rust_type.clone(),
3780            });
3781        }
3782    }
3783    // A correctly-spelled rule must not hide another rule that silently lost
3784    // the policy. Compare type names only after checking exact parsed spelling;
3785    // deliberate same-name types remain usable by listing each one explicitly.
3786    for selected in representation_types {
3787        if config
3788            .json_policy_types
3789            .iter()
3790            .any(|listed| context::rust_type_key(listed) == context::rust_type_key(selected))
3791        {
3792            continue;
3793        }
3794        let Some(selected_name) = context::rust_type_name(selected) else {
3795            continue;
3796        };
3797        if let Some(listed) = config.json_policy_types.iter().find(|listed| {
3798            context::rust_type_name(listed).as_deref() == Some(selected_name.as_str())
3799        }) {
3800            return Err(CodeGenError::JsonPolicyTypeNearMiss {
3801                selected: selected.clone(),
3802                listed: listed.clone(),
3803            });
3804        }
3805    }
3806
3807    // JSON strictness needs JSON deserializers to attach to. Warn once per run.
3808    if !config.generate_json
3809        && (config.deny_unknown_json_fields
3810            || config
3811                .deny_unknown_json_fields_in
3812                .iter()
3813                .any(|(_, enabled)| *enabled))
3814    {
3815        ctx.warn(CodeGenWarning::DenyUnknownJsonFieldsRequiresJson);
3816    }
3817
3818    // Same treatment for `deny_unknown_json_fields_in`: an inert enabling rule
3819    // leaves its messages silently ignoring unknown JSON keys, which is the
3820    // exact failure the rule was added to stop.
3821    for (rule, _) in &config.deny_unknown_json_fields_in {
3822        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
3823            ctx.warn(CodeGenWarning::DenyUnknownJsonFieldsRuleMatchedNothing {
3824                rule: rule.clone(),
3825            });
3826        }
3827    }
3828
3829    // Warn per inert `skip_debug` rule; `SkipDebugRuleMatchedNothing`
3830    // documents the consequence.
3831    for rule in &config.skip_debug {
3832        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate)
3833            && !rule_names_generated_enum(rule, file_descriptors, files_to_generate)
3834        {
3835            ctx.warn(CodeGenWarning::SkipDebugRuleMatchedNothing { rule: rule.clone() });
3836        }
3837    }
3838
3839    // A field-type rule that matches no generated field leaves the fields it
3840    // was written for on their default Rust type, and the build still
3841    // succeeds, so warn per rule.
3842    let field_type_rules = [
3843        ("bytes_fields", rule_paths(&config.bytes_fields)),
3844        ("string_fields", rule_paths(&config.string_fields)),
3845        ("map_fields", rule_paths(&config.map_fields)),
3846        ("repeated_fields", rule_paths(&config.repeated_fields)),
3847    ];
3848    let mut every_file: Option<Vec<String>> = None;
3849    for (option, rules) in field_type_rules {
3850        for rule in rules {
3851            if rule_matches_field_in(rule, file_descriptors, files_to_generate) {
3852                continue;
3853            }
3854            let every_file: &[String] = every_file.get_or_insert_with(|| {
3855                file_descriptors
3856                    .iter()
3857                    .filter_map(|fd| fd.name.clone())
3858                    .collect()
3859            });
3860            ctx.warn(CodeGenWarning::FieldTypeRuleMatchedNothing {
3861                rule: rule.clone(),
3862                option,
3863                matches_ungenerated: rule_matches_field_in(rule, file_descriptors, every_file),
3864            });
3865        }
3866    }
3867
3868    // A rule that names no generated message (typo, field path, extern-mapped
3869    // package) leaves its messages on the global strategy.
3870    for (rule, _) in &config.codec_strategy_in {
3871        if !rule_matches_generated_message(rule, file_descriptors, files_to_generate) {
3872            ctx.warn(CodeGenWarning::CodecStrategyRuleMatchedNothing { rule: rule.clone() });
3873        }
3874    }
3875    // Two fields with one number make the generated code wrong under either
3876    // codec. Checked before the table plan: a message that also cannot use
3877    // the table would otherwise get the plan's advice to select the unrolled
3878    // codec, which fails here too.
3879    for (file, _) in generated_files(file_descriptors, files_to_generate) {
3880        check_field_numbers(&file.message_type, file.package.as_deref().unwrap_or(""))?;
3881    }
3882    if ctx.table_codec_requested() {
3883        ctx.plan_table_codec(file_descriptors, files_to_generate)?;
3884    }
3885
3886    // Lazy views need the eager view machinery; warn once per run.
3887    if config.lazy_views && !config.generate_views {
3888        ctx.warn(CodeGenWarning::LazyViewsRequireViews);
3889    }
3890
3891    // Warn about exclude_packages entries that matched no package in the full
3892    // descriptor set — likely a typo or stale entry. Checked against
3893    // file_descriptors (not just files_to_generate) so plugin users without
3894    // include_imports don't get spurious warnings for packages they never
3895    // compiled in the first place.
3896    for package in &normalized_excludes {
3897        let matched = file_descriptors.iter().any(|fd| {
3898            package_is_excluded(
3899                fd.package.as_deref().unwrap_or(""),
3900                std::slice::from_ref(package),
3901            )
3902        });
3903        if !matched {
3904            ctx.warn(CodeGenWarning::ExcludePackageMatchedNothing {
3905                package: package.clone(),
3906            });
3907        }
3908    }
3909
3910    // Group requested files by package. BTreeMap → deterministic output order.
3911    let mut by_package: std::collections::BTreeMap<String, Vec<&FileDescriptorProto>> =
3912        std::collections::BTreeMap::new();
3913    let mut grouped = std::collections::HashSet::new();
3914    for file_name in files_to_generate {
3915        // A file listed twice is generated once.
3916        if !grouped.insert(file_name.as_str()) {
3917            continue;
3918        }
3919        let file_desc = file_descriptors
3920            .iter()
3921            .find(|f| f.name.as_deref() == Some(file_name.as_str()))
3922            .ok_or_else(|| CodeGenError::FileNotFound(file_name.clone()))?;
3923        let pkg = file_desc.package.as_deref().unwrap_or("").to_string();
3924        by_package.entry(pkg).or_default().push(file_desc);
3925    }
3926
3927    // Warn when a kept file references a type that is not being generated and
3928    // has no extern_path mapping. This catches exclude_package misuse (and
3929    // missing extern_path) before the consumer gets a dangling `super::…::Type`
3930    // compile error with no indication of the configuration gap.
3931    {
3932        let extern_paths = effective_extern_paths(file_descriptors, files_to_generate, config);
3933
3934        // Collect the FQNs of every type declared in a kept file.
3935        // These are always safe to reference (generated in place).
3936        let mut declared_in_kept: std::collections::HashSet<String> =
3937            std::collections::HashSet::new();
3938        for files in by_package.values() {
3939            for &file in files {
3940                collect_fqns_in_file(file, &mut declared_in_kept);
3941            }
3942        }
3943
3944        // Collect FQNs covered by file-level externs (e.g. descriptor.proto →
3945        // ::buffa_descriptor). These resolve externally even when the package-level
3946        // extern_paths don't cover them — suppressing false positives when the
3947        // auto-injected .google.protobuf package mapping is overridden.
3948        let file_extern_paths = effective_file_extern_paths(files_to_generate, config);
3949        let mut file_extern_covered: std::collections::HashSet<String> =
3950            std::collections::HashSet::new();
3951        for (fe_file, _) in &file_extern_paths {
3952            if let Some(fd) = file_descriptors
3953                .iter()
3954                .find(|f| f.name.as_deref() == Some(fe_file.as_str()))
3955            {
3956                collect_fqns_in_file(fd, &mut file_extern_covered);
3957            }
3958        }
3959
3960        let scan = ExcludedRefScan {
3961            ctx: &ctx,
3962            extern_paths: &extern_paths,
3963            declared_in_kept: &declared_in_kept,
3964            file_extern_covered: &file_extern_covered,
3965        };
3966        let mut warned: std::collections::HashSet<(String, String)> =
3967            std::collections::HashSet::new();
3968        for files in by_package.values() {
3969            for &file in files {
3970                let file_name = file.name.as_deref().unwrap_or("?");
3971                for msg in &file.message_type {
3972                    warn_excluded_refs_msg(scan, file_name, msg, "", &mut warned);
3973                }
3974                for ext in &file.extension {
3975                    warn_excluded_refs_field(scan, file_name, ext, "", &mut warned);
3976                }
3977            }
3978        }
3979    }
3980
3981    // Reflection: serialize the FileDescriptorSet once, regardless of how
3982    // many packages are in the request, so the build-time re-encoding cost
3983    // doesn't scale with the package count. In the default mode each package
3984    // embeds this copy; in shared-pool mode the bytes are embedded once by the
3985    // module-tree builder, not per package, so `generate` needs no copy at all.
3986    // In shared mode (without a `shared_descriptor_pool_root` override) the
3987    // tree root gains a `pub mod __buffa_fds`; reserve that name against user
3988    // packages/types the same way `__buffa` is reserved, so a
3989    // `package __buffa_fds;` (or a root-package type named `__buffa_fds`) fails
3990    // with a clear error instead of a duplicate-module collision at the root.
3991    // With an override the reservation is skipped for both absolute and
3992    // crate-relative roots: buffa cannot verify where the override points,
3993    // so a package/type actually named `__buffa_fds` in this tree would go
3994    // undetected rather than erroring here.
3995    if config.shared_descriptor_pool && config.shared_descriptor_pool_root.is_none() {
3996        validate_shared_root_name(file_descriptors, files_to_generate)?;
3997    }
3998
3999    // `file_descriptors` is the override-applied set (rebound above). The
4000    // default path embeds it directly; shared mode embeds nothing here and
4001    // leaves the single copy to the front-end, which must reproduce the same
4002    // overrides via `encode_descriptor_set`. On the plugin path — where the
4003    // packaging plugin can't see the override options — that combination is
4004    // rejected up front (see `protoc-gen-reallyme-buffa`).
4005    let fds_bytes = if config.generate_reflection && !config.shared_descriptor_pool {
4006        reflect::encode_fds_once(file_descriptors)
4007    } else {
4008        Vec::new()
4009    };
4010
4011    // Custom owned types used as elements of a `repeated` field need a
4012    // `ProtoElemJson` (JSON) and/or `ReflectElement` (vtable) impl, which buffa
4013    // cannot provide for a foreign type (orphan rule). Collect them once across
4014    // the whole request, render the impls, and hand them to the first package so
4015    // they are emitted exactly once (a per-package emit would collide, E0119).
4016    let custom_elems = collect_custom_elements(&ctx, file_descriptors, files_to_generate, false);
4017    let custom_elem_impls = render_custom_elem_impls(&ctx, &custom_elems)?;
4018
4019    let empty_impls = TokenStream::new();
4020    let mut output = Vec::new();
4021    let mut output_names = OutputNames::default();
4022    let mut custom_emitted = false;
4023    for (package, files) in by_package {
4024        let impls = if custom_emitted {
4025            &empty_impls
4026        } else {
4027            custom_emitted = true;
4028            &custom_elem_impls
4029        };
4030        generate_package(
4031            &ctx,
4032            &package,
4033            &files,
4034            &fds_bytes,
4035            impls,
4036            &mut output_names,
4037            &mut output,
4038        )?;
4039    }
4040
4041    Ok((output, ctx.take_warnings()))
4042}
4043
4044/// The output paths assigned so far in one [`generate`] call, each with the
4045/// input it was generated from, in the form
4046/// [`CodeGenError::OutputFileNameConflict`] documents.
4047#[derive(Default)]
4048struct OutputNames(std::collections::HashMap<String, String>);
4049
4050impl OutputNames {
4051    /// Records that `source` generates `file_name`.
4052    ///
4053    /// # Errors
4054    ///
4055    /// [`CodeGenError::OutputFileNameConflict`] if another input already
4056    /// generates `file_name`.
4057    fn claim(&mut self, file_name: &str, source: String) -> Result<(), CodeGenError> {
4058        use std::collections::hash_map::Entry;
4059        match self.0.entry(file_name.to_owned()) {
4060            Entry::Occupied(first) => Err(CodeGenError::OutputFileNameConflict {
4061                file_name: file_name.to_owned(),
4062                first_source: first.get().clone(),
4063                second_source: source,
4064            }),
4065            Entry::Vacant(slot) => {
4066                slot.insert(source);
4067                Ok(())
4068            }
4069        }
4070    }
4071}
4072
4073/// Generate a module tree that assembles per-package `.mod.rs` files into
4074/// nested `pub mod` blocks matching the protobuf package hierarchy.
4075///
4076/// Each entry is a `(mod_file_name, package)` pair where `package` is the
4077/// dot-separated protobuf package name (e.g., `"google.api"`) and
4078/// `mod_file_name` is the corresponding `<pkg>.mod.rs` (only
4079/// [`GeneratedFileKind::PackageMod`] outputs need wiring; per-proto
4080/// content files are reached via `include!` from the stitcher).
4081///
4082/// `include_mode` controls how `include!` paths are emitted.
4083///
4084/// `emit_inner_allow` adds a `#![allow(...)]` inner attribute at the top —
4085/// valid when the output is used directly as a module file (`mod.rs`),
4086/// invalid when consumed via `include!`.
4087pub fn generate_module_tree<F: AsRef<str>, P: AsRef<str>>(
4088    entries: &[(F, P)],
4089    include_mode: IncludeMode<'_>,
4090    emit_inner_allow: bool,
4091) -> String {
4092    use std::collections::BTreeMap;
4093    use std::fmt::Write;
4094
4095    use crate::idents::escape_mod_ident;
4096
4097    #[derive(Default)]
4098    struct ModNode {
4099        files: Vec<String>,
4100        children: BTreeMap<String, Self>,
4101    }
4102
4103    let mut root = ModNode::default();
4104
4105    for (file_name, package) in entries {
4106        let package = package.as_ref();
4107        let pkg_parts: Vec<&str> = if package.is_empty() {
4108            vec![]
4109        } else {
4110            package.split('.').collect()
4111        };
4112
4113        let mut node = &mut root;
4114        for seg in &pkg_parts {
4115            node = node.children.entry(seg.to_string()).or_default();
4116        }
4117        node.files.push(file_name.as_ref().to_string());
4118    }
4119
4120    let lints = ALLOW_LINTS.join(", ");
4121    let mut out = String::new();
4122    out.push_str(GENERATED_HEADER);
4123    if emit_inner_allow {
4124        let _ = writeln!(out, "#![allow({lints})]");
4125    }
4126    let _ = writeln!(out);
4127
4128    fn emit(out: &mut String, node: &ModNode, depth: usize, mode: IncludeMode<'_>, lints: &str) {
4129        let indent = "    ".repeat(depth);
4130
4131        for file in &node.files {
4132            match mode {
4133                IncludeMode::Relative(prefix) => {
4134                    let path = format!("{prefix}{file}");
4135                    let _ = writeln!(out, "{indent}include!({path:?});");
4136                }
4137                IncludeMode::OutDir => {
4138                    let path = format!("/{file}");
4139                    let _ = writeln!(
4140                        out,
4141                        "{indent}include!(concat!(env!(\"OUT_DIR\"), {path:?}));"
4142                    );
4143                }
4144            }
4145        }
4146
4147        for (name, child) in &node.children {
4148            let escaped = escape_mod_ident(name);
4149            let _ = writeln!(out, "{indent}#[allow({lints})]");
4150            let _ = writeln!(out, "{indent}pub mod {escaped} {{");
4151            let _ = writeln!(out, "{indent}    use super::*;");
4152            emit(out, child, depth + 1, mode, lints);
4153            let _ = writeln!(out, "{indent}}}");
4154        }
4155    }
4156
4157    emit(&mut out, &root, 0, include_mode, &lints);
4158    out
4159}
4160
4161/// How [`generate_module_tree`] emits `include!` paths.
4162#[derive(Debug, Clone, Copy)]
4163pub enum IncludeMode<'a> {
4164    /// `include!("<prefix><file>")` — relative to the including file.
4165    /// Prefix is typically `""` or `"gen/"`.
4166    Relative(&'a str),
4167    /// `include!(concat!(env!("OUT_DIR"), "/<file>"))` — for build.rs output.
4168    OutDir,
4169}
4170
4171/// The corpus-wide state `CodeGenContext` derives on every `generate()`
4172/// call — which oneof variants are unboxed, which message fields are stored
4173/// inline, and the raw comment text per fully-qualified name — none of which
4174/// depends on the extern paths that legitimately vary per call in a
4175/// one-crate-per-package workspace. Build one with [`SharedCorpusContext::new`]
4176/// from the whole corpus and set [`CodeGenConfig::shared_corpus_context`] on
4177/// every per-package config to skip that work on each call.
4178///
4179/// A context is only valid for the exact `files` and the same
4180/// `unboxed_oneof_fields`/`pointer_fields` it was built from; `generate`
4181/// checks both and returns [`CodeGenError::SharedCorpusContextMismatch`]
4182/// rather than emitting code resolved against a different corpus. The
4183/// context holds the corpus comment map for as long as any clone of it lives,
4184/// so drop it once code generation is done. Cloning shares the precomputed
4185/// state (`Arc`s inside), and the type is `Send + Sync`, so one context can
4186/// be handed to parallel per-package `generate()` calls.
4187///
4188/// # Examples
4189///
4190/// ```
4191/// use buffa_codegen::{CodeGenConfig, SharedCorpusContext};
4192/// # use buffa_codegen::generated::descriptor::FileDescriptorProto;
4193/// # let corpus: Vec<FileDescriptorProto> = Vec::new();
4194/// # let packages: Vec<(String, Vec<String>)> = Vec::new();
4195/// let base = CodeGenConfig::default();
4196/// let shared = SharedCorpusContext::new(&corpus, &base);
4197/// for (extern_prefix, files_to_generate) in packages {
4198///     let mut config = base.clone();
4199///     config.extern_paths.push((extern_prefix, "::other_crate".to_string()));
4200///     config.shared_corpus_context = Some(shared.clone());
4201///     let _files = buffa_codegen::generate(&corpus, &files_to_generate, &config)?;
4202/// }
4203/// # Ok::<(), buffa_codegen::CodeGenError>(())
4204/// ```
4205#[derive(Clone)]
4206pub struct SharedCorpusContext {
4207    /// The exact corpus this context was built from, compared by full
4208    /// structural equality in [`check`](Self::check) rather than just file
4209    /// names — see `check` for why.
4210    files: std::sync::Arc<Vec<generated::descriptor::FileDescriptorProto>>,
4211    unboxed_oneof_fields: std::sync::Arc<Vec<String>>,
4212    pointer_fields: std::sync::Arc<Vec<(String, PointerRepr)>>,
4213    unboxed_oneof_variants: std::sync::Arc<std::collections::HashSet<String>>,
4214    inlined_message_fields: std::sync::Arc<std::collections::HashSet<String>>,
4215    comment_map: std::sync::Arc<std::collections::HashMap<String, String>>,
4216}
4217
4218impl SharedCorpusContext {
4219    /// Precompute the corpus-wide state for `files` under `config`'s oneof
4220    /// and pointer-representation rules, for reuse across every `generate()`
4221    /// call that passes the same `files` and rules (see
4222    /// [`CodeGenConfig::shared_corpus_context`]).
4223    #[must_use]
4224    pub fn new(
4225        files: &[generated::descriptor::FileDescriptorProto],
4226        config: &CodeGenConfig,
4227    ) -> Self {
4228        let msg_index = oneof::message_index(files);
4229        let unboxed_oneof_variants = oneof::resolve_unboxed_variants(
4230            &msg_index,
4231            &config.unboxed_oneof_fields,
4232            &config.pointer_fields,
4233        );
4234        let inlined_message_fields = oneof::resolve_inlined_fields(
4235            &msg_index,
4236            &config.unboxed_oneof_fields,
4237            &config.pointer_fields,
4238        );
4239        let comment_map = files.iter().flat_map(comments::fqn_comments).collect();
4240        Self {
4241            files: std::sync::Arc::new(files.to_vec()),
4242            unboxed_oneof_fields: std::sync::Arc::new(config.unboxed_oneof_fields.clone()),
4243            pointer_fields: std::sync::Arc::new(config.pointer_fields.clone()),
4244            unboxed_oneof_variants: std::sync::Arc::new(unboxed_oneof_variants),
4245            inlined_message_fields: std::sync::Arc::new(inlined_message_fields),
4246            comment_map: std::sync::Arc::new(comment_map),
4247        }
4248    }
4249
4250    /// Refuse a context built from a different corpus or different
4251    /// oneof/pointer-repr rules than this call's. Compares the full corpus
4252    /// by structural equality rather than just file names, since
4253    /// `SharedCorpusContext` has no lifetime tying it to the caller's
4254    /// `files` — a `Vec` can keep its allocation across an ordinary
4255    /// `pop()` + `push()` of a different file, so a pointer/length check
4256    /// would be unsound. O(corpus) per call; ~25-28% added wall/CPU time on
4257    /// a 2895-crate corpus versus a name-only comparison, still a ~2.3x win
4258    /// over not sharing the context at all.
4259    pub(crate) fn check(
4260        &self,
4261        files: &[generated::descriptor::FileDescriptorProto],
4262        config: &CodeGenConfig,
4263    ) -> Result<(), CodeGenError> {
4264        let what = if *files != self.files[..] {
4265            "files"
4266        } else if *self.unboxed_oneof_fields != config.unboxed_oneof_fields {
4267            "unboxed_oneof_fields"
4268        } else if *self.pointer_fields != config.pointer_fields {
4269            "pointer_fields"
4270        } else {
4271            return Ok(());
4272        };
4273        Err(CodeGenError::SharedCorpusContextMismatch { what })
4274    }
4275
4276    pub(crate) fn unboxed_oneof_variants(
4277        &self,
4278    ) -> &std::sync::Arc<std::collections::HashSet<String>> {
4279        &self.unboxed_oneof_variants
4280    }
4281
4282    pub(crate) fn inlined_message_fields(
4283        &self,
4284    ) -> &std::sync::Arc<std::collections::HashSet<String>> {
4285        &self.inlined_message_fields
4286    }
4287
4288    pub(crate) fn comment_map(&self) -> &std::sync::Arc<std::collections::HashMap<String, String>> {
4289        &self.comment_map
4290    }
4291}
4292
4293// The comment map is the whole corpus's comment text; print sizes, not
4294// contents, so a `{:?}` of a `CodeGenConfig` stays readable.
4295impl core::fmt::Debug for SharedCorpusContext {
4296    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
4297        f.debug_struct("SharedCorpusContext")
4298            .field("files", &self.files.len())
4299            .field("unboxed_oneof_variants", &self.unboxed_oneof_variants.len())
4300            .field("inlined_message_fields", &self.inlined_message_fields.len())
4301            .field("comments", &self.comment_map.len())
4302            .finish()
4303    }
4304}
4305
4306/// Encode the shared reflection `FileDescriptorSet` for a codegen run, with
4307/// `source_code_info` stripped, ready to embed once at the module-tree root in
4308/// [shared-pool mode](CodeGenConfig::shared_descriptor_pool).
4309///
4310/// `file_descriptors` is the full transitive closure (the same slice passed to
4311/// [`generate`]). Front-ends (`buffa-build`, `protoc-gen-reallyme-buffa-packaging`)
4312/// call this to obtain the single copy of the bytes, then hand them to
4313/// [`shared_descriptor_root_module`].
4314#[must_use]
4315pub fn encode_descriptor_set(
4316    file_descriptors: &[generated::descriptor::FileDescriptorProto],
4317    feature_overrides: &[(String, FeatureOverride)],
4318) -> Vec<u8> {
4319    // `generate` applies feature overrides to the descriptors up front and the
4320    // default (non-shared) path embeds *that* override-applied set, so the
4321    // embedded reflection descriptors match the generated code. Shared mode
4322    // skips `generate`'s encode, so any front-end computing the shared copy
4323    // here must apply the same transform — otherwise the shared pool reports
4324    // un-overridden features (e.g. an `open_enums_in` enum still closed) and
4325    // disagrees with the code. Pass the same `feature_overrides` the codegen
4326    // config carries; `&[]` when none are configured (the common case, a
4327    // borrow with no clone).
4328    let overridden =
4329        feature_overrides::apply_feature_overrides(file_descriptors, feature_overrides);
4330    let files = overridden.as_ref().map_or(file_descriptors, |o| &o.files);
4331    reflect::encode_fds_once(files)
4332}
4333
4334/// How [`shared_descriptor_root_module`] embeds the descriptor set into the
4335/// generated tree. Both forms decode to byte-identical runtime data; they
4336/// differ only in generated-source size and whether a sidecar file is written.
4337#[derive(Debug, Clone, Copy)]
4338#[non_exhaustive]
4339pub enum FdsEmbedding<'a> {
4340    /// Embed the bytes inline as a byte-string literal. Self-contained: no extra
4341    /// file, but the descriptor bytes cost several times their size in
4342    /// generated Rust source. This is all the plugin path can do, since
4343    /// protoc's `CodeGeneratorResponse` carries only UTF-8 text.
4344    Inline,
4345    /// `include_bytes!` a sidecar file the caller writes next to the generated
4346    /// tree, keeping the bytes out of the Rust source entirely. `file_name` is
4347    /// the sidecar's name; `mode` mirrors [`generate_module_tree`]'s —
4348    /// [`IncludeMode::Relative`] for a checked-in sibling,
4349    /// [`IncludeMode::OutDir`] for build-script output. The caller is
4350    /// responsible for writing `fds_bytes` to that file.
4351    Sidecar {
4352        file_name: &'a str,
4353        mode: IncludeMode<'a>,
4354    },
4355}
4356
4357/// Render the shared `__buffa_fds` root module as formatted Rust source, for a
4358/// front-end to prepend to the module-tree file in
4359/// [shared-pool mode](CodeGenConfig::shared_descriptor_pool). Every package's
4360/// `__buffa::reflect` module delegates here, so the descriptor set is embedded
4361/// once for the whole tree instead of once per package.
4362///
4363/// `fds_bytes` is the output of [`encode_descriptor_set`]. `embedding` chooses
4364/// inline vs. an `include_bytes!` sidecar (see [`FdsEmbedding`]). `gate` wraps
4365/// the module in `#[cfg(feature = "<gate>")]` when `Some`, to match
4366/// [`CodeGenConfig::reflect_feature_gate`] (so the root module and the
4367/// per-package delegations appear and disappear together); pass `None` when
4368/// reflection is unconditional.
4369///
4370/// # Panics
4371///
4372/// Panics if the rendered module fails to parse — it is machine-generated, so
4373/// a parse failure is a codegen bug.
4374#[must_use]
4375pub fn shared_descriptor_root_module(
4376    fds_bytes: &[u8],
4377    embedding: FdsEmbedding<'_>,
4378    gate: Option<&str>,
4379) -> String {
4380    let source = match embedding {
4381        FdsEmbedding::Inline => reflect::FdsSource::Inline(fds_bytes),
4382        FdsEmbedding::Sidecar {
4383            file_name,
4384            mode: IncludeMode::Relative(prefix),
4385        } => {
4386            let path = format!("{prefix}{file_name}");
4387            reflect::FdsSource::IncludeBytes(quote::quote! { #path })
4388        }
4389        FdsEmbedding::Sidecar {
4390            file_name,
4391            mode: IncludeMode::OutDir,
4392        } => {
4393            let slash_name = format!("/{file_name}");
4394            reflect::FdsSource::IncludeBytes(
4395                quote::quote! { concat!(env!("OUT_DIR"), #slash_name) },
4396            )
4397        }
4398    };
4399    let tokens = feature_gates::cfg_block(reflect::shared_root_module(source), gate);
4400    let file = syn::parse2::<syn::File>(tokens)
4401        .expect("shared descriptor root module must parse as a Rust file");
4402    prettyplease::unparse(&file)
4403}
4404
4405/// Validate [`CodeGenConfig::shared_descriptor_pool_root`]'s string form: an
4406/// absolute (`::`-prefixed) or `crate`-relative path of plain `::`-separated
4407/// identifiers, no generic or parenthesized arguments.
4408///
4409/// `syn::Path` alone isn't strict enough here — it happily parses
4410/// `::k::__buffa_fds<T>`, which would then splice into uncompilable
4411/// generated code (`pub use ::k::__buffa_fds<T>::FILE_DESCRIPTOR_SET_BYTES;`),
4412/// exactly the downstream failure this check exists to prevent. A leading
4413/// `::` or `crate` is required because the same string is spliced verbatim
4414/// at every package depth in the tree — a plain relative path could only
4415/// ever be correct from one depth.
4416fn validate_shared_root_path(path: &str) -> Result<(), CodeGenError> {
4417    let is_absolute = path.starts_with("::");
4418    let is_crate_relative = path == "crate" || path.starts_with("crate::");
4419    if !is_absolute && !is_crate_relative {
4420        return Err(CodeGenError::Other(format!(
4421            "shared_descriptor_pool_root must be an absolute (`::`-prefixed) or \
4422             crate-relative (`crate`-prefixed) path — the same value is spliced \
4423             verbatim at every package depth, so a plain relative path would only \
4424             be correct from one depth: {path:?}"
4425        )));
4426    }
4427    let rest = path.strip_prefix("::").unwrap_or(path);
4428    if rest.is_empty() {
4429        return Err(CodeGenError::Other(format!(
4430            "shared_descriptor_pool_root has no path after the `::` prefix: {path:?}"
4431        )));
4432    }
4433    for (i, segment) in rest.split("::").enumerate() {
4434        let mut chars = segment.chars();
4435        let is_ident = chars
4436            .next()
4437            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
4438            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_');
4439        if !is_ident {
4440            return Err(CodeGenError::Other(format!(
4441                "shared_descriptor_pool_root segment {segment:?} is not a plain \
4442                 identifier (no generic or parenthesized arguments, ASCII only) — \
4443                 the value is spliced verbatim into generated code: {path:?}"
4444            )));
4445        }
4446        // `_`, `self`, `Self` and `super` are identifiers to the scan above but
4447        // not usable path segments; `crate` is only legal first.
4448        let is_path_keyword =
4449            matches!(segment, "_" | "self" | "Self" | "super") || (i > 0 && segment == "crate");
4450        if is_path_keyword {
4451            return Err(CodeGenError::Other(format!(
4452                "shared_descriptor_pool_root segment {segment:?} is a path keyword \
4453                 and cannot be spliced into generated code: {path:?}"
4454            )));
4455        }
4456    }
4457    Ok(())
4458}
4459
4460/// Reject user names that would collide with the shared descriptor root module
4461/// (`reflect::SHARED_ROOT_MOD`) placed at the module-tree root in shared-pool
4462/// mode. Mirrors how [`SENTINEL_MOD`](context::SENTINEL_MOD)/`__buffa` is
4463/// reserved: any package segment equal to the reserved name, plus a
4464/// root-package (unnamed) message whose *module* name (snake_cased, matching
4465/// `validate_file`) or a file-level enum name equals it.
4466///
4467/// Only files actually being generated are checked — an import-only package
4468/// named `__buffa_fds` emits no module, so it must not trip this guard.
4469fn validate_shared_root_name(
4470    files: &[FileDescriptorProto],
4471    files_to_generate: &[String],
4472) -> Result<(), CodeGenError> {
4473    use std::collections::HashSet;
4474
4475    let reserved = reflect::SHARED_ROOT_MOD;
4476    let generated: HashSet<&str> = files_to_generate.iter().map(String::as_str).collect();
4477    let reserved_err = |location: String| CodeGenError::ReservedModuleName {
4478        name: reserved.to_string(),
4479        location,
4480    };
4481
4482    for file in files {
4483        if !generated.contains(file.name.as_deref().unwrap_or("")) {
4484            continue;
4485        }
4486        let package = file.package.as_deref().unwrap_or("");
4487        // Every package segment becomes a `pub mod <seg>`; the reserved name in
4488        // any of them collides with the tree-root `__buffa_fds`.
4489        if package.split('.').any(|seg| seg == reserved) {
4490            return Err(reserved_err(format!(
4491                "package '{package}' (reserved by shared_descriptor_pool)"
4492            )));
4493        }
4494        // Only the unnamed root package puts items beside `__buffa_fds`; named
4495        // packages nest theirs under `pub mod <segment>`. A message's
4496        // nested-types module is snake_cased (like `validate_file`), so compare
4497        // against that; file-level enums are emitted verbatim.
4498        if package.is_empty() {
4499            for m in &file.message_type {
4500                let name = m.name.as_deref().unwrap_or("");
4501                if crate::oneof::to_snake_case(name) == reserved {
4502                    return Err(reserved_err(format!(
4503                        "message '{name}' (its module `{reserved}` is reserved by \
4504                         shared_descriptor_pool)"
4505                    )));
4506                }
4507            }
4508            for e in &file.enum_type {
4509                if e.name.as_deref() == Some(reserved) {
4510                    return Err(reserved_err(format!(
4511                        "enum '{reserved}' (reserved by shared_descriptor_pool)"
4512                    )));
4513                }
4514            }
4515        }
4516    }
4517    Ok(())
4518}
4519
4520/// Rejects two sibling types that [`idents::local_type_name`] maps to one
4521/// Rust name. An empty name is skipped; [`required_type_name`] reports it.
4522fn check_type_names<'a>(
4523    scope: &str,
4524    names: impl Iterator<Item = &'a str>,
4525    type_name_prefix: &str,
4526) -> Result<(), CodeGenError> {
4527    let mut seen: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
4528    for name in names.filter(|name| !name.is_empty()) {
4529        let rust_name = idents::local_type_name(type_name_prefix, name);
4530        if let Some(first) = seen.insert(rust_name.clone(), name) {
4531            return Err(CodeGenError::TypeNameConflict {
4532                scope: scope.to_string(),
4533                first_type: first.to_string(),
4534                second_type: name.to_string(),
4535                rust_name,
4536            });
4537        }
4538    }
4539    Ok(())
4540}
4541
4542/// Returns [`CodeGenError::DuplicateFieldNumber`] for the first message of
4543/// `messages`, or nested in one, that has two fields with one number.
4544/// `scope` is the full name of what contains `messages`: the package, or the
4545/// enclosing message.
4546///
4547/// A oneof member is a field of the message, so it is compared with every
4548/// other field. An extension declared in the message is a field of its
4549/// extendee, so it is not compared with the message's own fields, and an
4550/// extension's number is not checked against its extendee here.
4551fn check_field_numbers(
4552    messages: &[crate::generated::descriptor::DescriptorProto],
4553    scope: &str,
4554) -> Result<(), CodeGenError> {
4555    for msg in messages {
4556        let name = msg.name.as_deref().unwrap_or("");
4557        let fqn = if scope.is_empty() {
4558            name.to_string()
4559        } else {
4560            format!("{scope}.{name}")
4561        };
4562        let mut seen: std::collections::HashMap<i32, &str> = std::collections::HashMap::new();
4563        for field in &msg.field {
4564            let Some(number) = field.number else {
4565                continue;
4566            };
4567            let field_name = field.name.as_deref().unwrap_or("");
4568            if let Some(first) = seen.insert(number, field_name) {
4569                return Err(CodeGenError::DuplicateFieldNumber {
4570                    message_name: fqn,
4571                    first_field: first.to_string(),
4572                    second_field: field_name.to_string(),
4573                    number,
4574                });
4575            }
4576        }
4577        check_field_numbers(&msg.nested_type, &fqn)?;
4578    }
4579    Ok(())
4580}
4581
4582/// Validate one input descriptor before generating code for it.
4583///
4584/// Checks, in one walk of the message tree:
4585///
4586/// - **Required type names**: every message and enum has a non-empty name.
4587/// - **Reserved field names**: no field starts with `__buffa_` (would clash
4588///   with generated `__buffa_unknown_fields` / `__buffa_cached_size`).
4589/// - **Module-name conflicts**: no two sibling messages snake_case to the
4590///   same module name (e.g. `HTTPRequest` vs `HttpRequest`).
4591/// - **Type-name conflicts**: no two messages or enums nested in one message
4592///   escape to the same Rust type name (e.g. `bool` vs `bool_`). The caller
4593///   checks the package-level types, which span files.
4594/// - **Reserved sentinel**: no package segment, message-module name, or
4595///   file-level enum name equals [`SENTINEL_MOD`](context::SENTINEL_MOD).
4596///   Ancillary types live under `pkg::__buffa::…`; a proto element
4597///   emitting an item named `__buffa` at package root would produce
4598///   E0428 against `pub mod __buffa`. This is the only name buffa
4599///   reserves in user namespace.
4600fn validate_file(file: &FileDescriptorProto, type_name_prefix: &str) -> Result<(), CodeGenError> {
4601    use std::collections::HashMap;
4602
4603    let sentinel = context::SENTINEL_MOD;
4604    let package = file.package.as_deref().unwrap_or("");
4605    if package.split('.').any(|seg| seg == sentinel) {
4606        return Err(CodeGenError::ReservedModuleName {
4607            name: sentinel.to_string(),
4608            location: format!("package '{package}'"),
4609        });
4610    }
4611    // File-level enums emit `pub enum <name>` at package root with the
4612    // proto name preserved verbatim (no PascalCase normalization), so a
4613    // proto `enum __buffa` would land beside `pub mod __buffa`. Nested
4614    // enums live inside their owner message's module and cannot collide
4615    // with the package-root sentinel, so only file-level is checked.
4616    for enum_type in &file.enum_type {
4617        let name = required_type_name(enum_type.name.as_deref(), "enum.name")?;
4618        if name == sentinel {
4619            return Err(CodeGenError::ReservedModuleName {
4620                name: sentinel.to_string(),
4621                location: format!("enum '{package}.{name}'"),
4622            });
4623        }
4624    }
4625
4626    fn walk(
4627        messages: &[crate::generated::descriptor::DescriptorProto],
4628        scope: &str,
4629        sentinel: &str,
4630        type_name_prefix: &str,
4631    ) -> Result<(), CodeGenError> {
4632        // snake_case module name → original proto name (for conflict diag).
4633        let mut seen: HashMap<String, &str> = HashMap::new();
4634
4635        for msg in messages {
4636            let name = required_type_name(msg.name.as_deref(), "message.name")?;
4637            let fqn = if scope.is_empty() {
4638                name.to_string()
4639            } else {
4640                format!("{scope}.{name}")
4641            };
4642
4643            for enum_type in &msg.enum_type {
4644                required_type_name(enum_type.name.as_deref(), "enum.name")?;
4645            }
4646            check_type_names(
4647                &fqn,
4648                msg.nested_type
4649                    .iter()
4650                    .filter_map(|m| m.name.as_deref())
4651                    .chain(msg.enum_type.iter().filter_map(|e| e.name.as_deref())),
4652                type_name_prefix,
4653            )?;
4654
4655            for field in &msg.field {
4656                if let Some(fname) = &field.name {
4657                    if fname.starts_with("__buffa_") {
4658                        return Err(CodeGenError::ReservedFieldName {
4659                            message_name: fqn,
4660                            field_name: fname.clone(),
4661                        });
4662                    }
4663                }
4664            }
4665
4666            let module_name = crate::oneof::to_snake_case(name);
4667            if module_name == sentinel {
4668                return Err(CodeGenError::ReservedModuleName {
4669                    name: sentinel.to_string(),
4670                    location: format!("message '{fqn}'"),
4671                });
4672            }
4673            if let Some(existing) = seen.get(&module_name) {
4674                return Err(CodeGenError::ModuleNameConflict {
4675                    scope: scope.to_string(),
4676                    name_a: existing.to_string(),
4677                    name_b: name.to_string(),
4678                    module_name,
4679                });
4680            }
4681            seen.insert(module_name, name);
4682
4683            walk(&msg.nested_type, &fqn, sentinel, type_name_prefix)?;
4684        }
4685        Ok(())
4686    }
4687
4688    walk(&file.message_type, package, sentinel, type_name_prefix)
4689}
4690
4691/// Returns the name of a message or enum descriptor, or
4692/// [`CodeGenError::MissingField`]`(field)` if the name is absent or empty.
4693///
4694/// An empty name cannot be a Rust identifier, so it is rejected like an
4695/// absent one.
4696fn required_type_name<'a>(
4697    name: Option<&'a str>,
4698    field: &'static str,
4699) -> Result<&'a str, CodeGenError> {
4700    name.filter(|name| !name.is_empty())
4701        .ok_or(CodeGenError::MissingField(field))
4702}
4703
4704/// Per-proto content streams plus the file stem, ready to be formatted.
4705struct ProtoContent {
4706    stem: String,
4707    owned: TokenStream,
4708    view: TokenStream,
4709    lazy_view: TokenStream,
4710    oneof: TokenStream,
4711    view_oneof: TokenStream,
4712    ext: TokenStream,
4713    /// Candidate `pub use` re-exports targeting the package root (top-level
4714    /// view structs, file-level extension consts). Filtered against the
4715    /// package-wide root namespace in [`generate_package_mod`] — the package
4716    /// can span multiple `.proto` files, so collisions are only knowable at
4717    /// the stitcher level.
4718    root_reexports: Vec<message::ReexportCandidate>,
4719}
4720
4721/// Generate the per-`.proto` content token streams for one input file.
4722/// Each ancillary kind that has no content yields an empty stream and
4723/// is dropped at the file-emission stage.
4724fn generate_proto_content(
4725    ctx: &context::CodeGenContext,
4726    current_package: &str,
4727    file: &FileDescriptorProto,
4728    reg: &mut message::RegistryPaths,
4729) -> Result<ProtoContent, CodeGenError> {
4730    use crate::idents::make_field_ident;
4731    use crate::message::MessageOutput;
4732
4733    validate_file(file, &ctx.config.type_name_prefix)?;
4734
4735    let resolver = imports::ImportResolver::new();
4736    let features = crate::features::for_file(file);
4737
4738    let mut owned = TokenStream::new();
4739    let mut view = TokenStream::new();
4740    let mut lazy_view = TokenStream::new();
4741    let mut oneof = TokenStream::new();
4742    let mut view_oneof = TokenStream::new();
4743    let mut ext = TokenStream::new();
4744    let mut root_reexports: Vec<message::ReexportCandidate> = Vec::new();
4745    let sentinel = make_field_ident(context::SENTINEL_MOD);
4746
4747    for enum_type in &file.enum_type {
4748        let enum_proto_name = enum_type.name.as_deref().unwrap_or("");
4749        let enum_rust_name = ctx.config.prefixed_type_name(enum_proto_name);
4750        let enum_fqn = if current_package.is_empty() {
4751            enum_proto_name.to_string()
4752        } else {
4753            format!("{}.{}", current_package, enum_proto_name)
4754        };
4755        owned.extend(enumeration::generate_enum(
4756            ctx,
4757            enum_type,
4758            &enum_rust_name,
4759            &enum_fqn,
4760            &features,
4761            &resolver,
4762        )?);
4763    }
4764
4765    for message_type in &file.message_type {
4766        let top_level_name = message_type.name.as_deref().unwrap_or("");
4767        let rust_name = ctx.config.prefixed_type_name(top_level_name);
4768        let proto_fqn = if current_package.is_empty() {
4769            top_level_name.to_string()
4770        } else {
4771            format!("{}.{}", current_package, top_level_name)
4772        };
4773        let MessageOutput {
4774            owned_top,
4775            owned_mod,
4776            oneof_tree: msg_oneof,
4777            view_tree: msg_view,
4778            lazy_view_tree: msg_lazy_view,
4779            view_oneof_tree: msg_view_oneof,
4780            reg: msg_reg,
4781        } = message::generate_message(
4782            ctx,
4783            message_type,
4784            current_package,
4785            &rust_name,
4786            &proto_fqn,
4787            &crate::features::message_scope_features(&features, message_type, true),
4788            &resolver,
4789        )?;
4790        owned.extend(owned_top);
4791        let mod_name = ctx.nested_module_name(current_package, top_level_name);
4792        let mod_ident = make_field_ident(&mod_name);
4793        let mod_doc = message::module_rename_doc(top_level_name, &mod_name);
4794        for p in msg_reg.json_ext {
4795            reg.json_ext.push(quote! { #mod_ident :: #p });
4796        }
4797        for p in msg_reg.text_ext {
4798            reg.text_ext.push(quote! { #mod_ident :: #p });
4799        }
4800        reg.json_any.extend(msg_reg.json_any);
4801        reg.text_any.extend(msg_reg.text_any);
4802
4803        if !owned_mod.is_empty() {
4804            owned.extend(quote! {
4805                #mod_doc
4806                pub mod #mod_ident {
4807                    #[allow(unused_imports)]
4808                    use super::*;
4809                    #owned_mod
4810                }
4811            });
4812        }
4813        oneof.extend(msg_oneof);
4814        view.extend(msg_view);
4815        lazy_view.extend(msg_lazy_view);
4816        view_oneof.extend(msg_view_oneof);
4817
4818        // Top-level message view → re-export at package root. The leading
4819        // `self::` is load-bearing: when consumers nest packages with
4820        // `pub mod a { use super::*; pub mod a_b { use super::*; … } }`
4821        // (`buffa-build`'s `_include.rs` does this), a parent package's
4822        // `__buffa` is in scope via the glob, and Rust's import-resolution
4823        // pass treats a glob-imported name as ambiguous against a
4824        // **macro-expanded** local one (the `pub mod __buffa` block arrives
4825        // via `include!()`), even though a non-macro local definition would
4826        // shadow the glob — see rustc E0659. `self::` resolves it
4827        // deterministically. `#[doc(inline)]` makes rustdoc render the type's
4828        // full page at the natural path instead of a "Re-export of …" stub.
4829        if ctx.config.generate_views {
4830            let view_ident = format_ident!("{rust_name}View");
4831            root_reexports.push(message::ReexportCandidate {
4832                name: view_ident.to_string(),
4833                tokens: feature_gates::cfg_block(
4834                    quote! {
4835                        #[doc(inline)]
4836                        pub use self :: #sentinel :: view :: #view_ident;
4837                    },
4838                    ctx.config.feature_gates().views,
4839                ),
4840            });
4841            // The owned-view wrapper gets the same natural-path treatment as
4842            // the view struct, so `pkg::FooOwnedView` works out of the box.
4843            let owned_view_ident = format_ident!("{rust_name}OwnedView");
4844            root_reexports.push(message::ReexportCandidate {
4845                name: owned_view_ident.to_string(),
4846                tokens: feature_gates::cfg_block(
4847                    quote! {
4848                        #[doc(inline)]
4849                        pub use self :: #sentinel :: view :: #owned_view_ident;
4850                    },
4851                    ctx.config.feature_gates().views,
4852                ),
4853            });
4854            if ctx.config.lazy_views {
4855                let lazy_ident = format_ident!("{rust_name}LazyView");
4856                root_reexports.push(message::ReexportCandidate {
4857                    name: lazy_ident.to_string(),
4858                    tokens: feature_gates::cfg_block(
4859                        quote! {
4860                            #[doc(inline)]
4861                            pub use self :: #sentinel :: lazy_view :: #lazy_ident;
4862                        },
4863                        ctx.config.feature_gates().views,
4864                    ),
4865                });
4866            }
4867        }
4868    }
4869
4870    // File-level `extend` declarations → `__buffa::ext::` (depth 2).
4871    let (file_ext_tokens, file_ext_json, file_ext_text) = extension::generate_extensions(
4872        ctx,
4873        &file.extension,
4874        current_package,
4875        2,
4876        &features,
4877        current_package,
4878    )?;
4879    ext.extend(file_ext_tokens);
4880    for id in file_ext_json {
4881        reg.json_ext.push(quote! { #sentinel :: ext :: #id });
4882    }
4883    for id in file_ext_text {
4884        reg.text_ext.push(quote! { #sentinel :: ext :: #id });
4885    }
4886    // File-level extension consts → re-export at package root. `self::` and
4887    // `#[doc(inline)]` for the same reasons as the view re-exports above.
4888    for ext_field in &file.extension {
4889        let const_ident = extension::extension_const_ident(ext_field.name.as_deref().unwrap_or(""));
4890        root_reexports.push(message::ReexportCandidate {
4891            name: const_ident.to_string(),
4892            tokens: quote! {
4893                #[doc(inline)]
4894                pub use self :: #sentinel :: ext :: #const_ident;
4895            },
4896        });
4897    }
4898
4899    Ok(ProtoContent {
4900        stem: proto_path_to_stem(file.name.as_deref().unwrap_or("")),
4901        owned,
4902        view,
4903        lazy_view,
4904        oneof,
4905        view_oneof,
4906        ext,
4907        root_reexports,
4908    })
4909}
4910
4911/// Per-section token streams for one package, ready for the stitcher.
4912///
4913/// In per-file mode each section holds `include!("<stem>...rs")` calls; in
4914/// `file_per_package` mode each holds the actual generated items.
4915#[derive(Default)]
4916struct PackageSections {
4917    owned: Vec<TokenStream>,
4918    view: Vec<TokenStream>,
4919    lazy_view: Vec<TokenStream>,
4920    oneof: Vec<TokenStream>,
4921    view_oneof: Vec<TokenStream>,
4922    ext: Vec<TokenStream>,
4923}
4924
4925impl PackageSections {
4926    /// Append one proto file's generated items in-line.
4927    ///
4928    /// Empty streams are skipped so each section's emptiness reflects
4929    /// "the package has no content of this kind" — symmetric with the
4930    /// per-file branch that filters at file-emission time.
4931    fn push_inline(&mut self, pc: ProtoContent) {
4932        let push_if_nonempty = |dst: &mut Vec<TokenStream>, ts: TokenStream| {
4933            if !ts.is_empty() {
4934                dst.push(ts);
4935            }
4936        };
4937        push_if_nonempty(&mut self.owned, pc.owned);
4938        push_if_nonempty(&mut self.view, pc.view);
4939        push_if_nonempty(&mut self.lazy_view, pc.lazy_view);
4940        push_if_nonempty(&mut self.oneof, pc.oneof);
4941        push_if_nonempty(&mut self.view_oneof, pc.view_oneof);
4942        push_if_nonempty(&mut self.ext, pc.ext);
4943    }
4944}
4945
4946/// Generate all output files for one proto package: up to five content
4947/// files per `.proto` (empty ancillary kinds are skipped) plus one
4948/// `<pkg>.mod.rs` stitcher, or a single `<pkg>.rs` when
4949/// [`CodeGenConfig::file_per_package`] is set.
4950fn generate_package(
4951    ctx: &context::CodeGenContext,
4952    current_package: &str,
4953    files: &[&FileDescriptorProto],
4954    fds_bytes: &[u8],
4955    // Deduped `ProtoElemJson` / `ReflectElement` impls for custom repeated
4956    // element types, collected generation-wide and emitted into exactly one
4957    // package's `__buffa` module (empty for every package but the first).
4958    custom_elem_impls: &TokenStream,
4959    output_names: &mut OutputNames,
4960    out: &mut Vec<GeneratedFile>,
4961) -> Result<(), CodeGenError> {
4962    // Registry paths are package-root-relative; `register_types` lives at
4963    // `__buffa::register_types` (one level deep), so each path gets a
4964    // single `super::` prefix when emitted into the fn body.
4965    let mut reg = message::RegistryPaths::default();
4966    let mut root_reexports: Vec<message::ReexportCandidate> = Vec::new();
4967
4968    // Package-level types share one module whichever file declares them.
4969    check_type_names(
4970        current_package,
4971        files.iter().flat_map(|file| {
4972            file.message_type
4973                .iter()
4974                .filter_map(|m| m.name.as_deref())
4975                .chain(file.enum_type.iter().filter_map(|e| e.name.as_deref()))
4976        }),
4977        &ctx.config.type_name_prefix,
4978    )?;
4979
4980    // Idiomatic imports: dry-run the package's generation once with the
4981    // registry collecting, so the set of package-root path references is
4982    // known — by construction, exactly the set the real pass will emit —
4983    // then assign short names and generate for real with the registry
4984    // resolving. Generation is deterministic, so the two passes see the
4985    // same references; assignment sorts the collected set, so the result
4986    // is also stable under `.proto` file reordering. The dry run's other
4987    // outputs (tokens, registry paths, re-export candidates, warnings) are
4988    // discarded; only the candidate *names* feed the occupied set, since a
4989    // surviving re-export occupies a root name a `use` must not claim.
4990    if ctx.config.idiomatic_imports && ctx.config.file_per_package {
4991        ctx.imports_begin_collecting();
4992        let warn_mark = ctx.warnings_len();
4993        let mut scratch_reg = message::RegistryPaths::default();
4994        let mut occupied = root_occupied_names(ctx, files);
4995        for file in files {
4996            let pc = generate_proto_content(ctx, current_package, file, &mut scratch_reg)?;
4997            occupied.extend(pc.root_reexports.into_iter().map(|c| c.name));
4998        }
4999        ctx.truncate_warnings(warn_mark);
5000        occupied.insert("register_types".to_string());
5001        // The reflect re-export names (`descriptor_pool`,
5002        // `FILE_DESCRIPTOR_SET_BYTES`) are reserved inside
5003        // `root_occupied_names` itself.
5004        let collected = ctx.imports_take_collected();
5005        ctx.imports_set_resolving(imports::RootImports::assign(&collected, &occupied));
5006    }
5007
5008    let sections = if ctx.config.file_per_package {
5009        let mut sections = PackageSections::default();
5010        for file in files {
5011            let mut pc = generate_proto_content(ctx, current_package, file, &mut reg)?;
5012            root_reexports.append(&mut pc.root_reexports);
5013            sections.push_inline(pc);
5014        }
5015        sections
5016    } else {
5017        let mut sections = PackageSections::default();
5018        for file in files {
5019            let mut pc = generate_proto_content(ctx, current_package, file, &mut reg)?;
5020            root_reexports.append(&mut pc.root_reexports);
5021            let source = file.name.as_deref().unwrap_or("");
5022            let stem = pc.stem;
5023
5024            // Empty ancillary token streams are skipped — neither the
5025            // content file nor the stitcher's `include!` is emitted.
5026            let emit = |suffix: &str,
5027                        kind: GeneratedFileKind,
5028                        tokens: TokenStream,
5029                        section: &mut Vec<TokenStream>,
5030                        output_names: &mut OutputNames,
5031                        out: &mut Vec<GeneratedFile>|
5032             -> Result<(), CodeGenError> {
5033                if tokens.is_empty() {
5034                    return Ok(());
5035                }
5036                let name = format!("{stem}{suffix}.rs");
5037                output_names.claim(&name, source.to_owned())?;
5038                section.push(quote! { include!(#name); });
5039                out.push(GeneratedFile {
5040                    name,
5041                    package: current_package.to_string(),
5042                    kind,
5043                    content: format_tokens(tokens, source)?,
5044                });
5045                Ok(())
5046            };
5047            emit(
5048                "",
5049                GeneratedFileKind::Owned,
5050                pc.owned,
5051                &mut sections.owned,
5052                output_names,
5053                out,
5054            )?;
5055            emit(
5056                ".__view",
5057                GeneratedFileKind::View,
5058                pc.view,
5059                &mut sections.view,
5060                output_names,
5061                out,
5062            )?;
5063            emit(
5064                ".__lazy_view",
5065                GeneratedFileKind::LazyView,
5066                pc.lazy_view,
5067                &mut sections.lazy_view,
5068                output_names,
5069                out,
5070            )?;
5071            emit(
5072                ".__oneof",
5073                GeneratedFileKind::Oneof,
5074                pc.oneof,
5075                &mut sections.oneof,
5076                output_names,
5077                out,
5078            )?;
5079            emit(
5080                ".__view_oneof",
5081                GeneratedFileKind::ViewOneof,
5082                pc.view_oneof,
5083                &mut sections.view_oneof,
5084                output_names,
5085                out,
5086            )?;
5087            emit(
5088                ".__ext",
5089                GeneratedFileKind::Ext,
5090                pc.ext,
5091                &mut sections.ext,
5092                output_names,
5093                out,
5094            )?;
5095        }
5096        sections
5097    };
5098
5099    let reexport_block = surviving_root_reexports(ctx, files, &reg, root_reexports);
5100
5101    let mod_name = if ctx.config.file_per_package {
5102        package_to_filename(current_package)
5103    } else {
5104        package_to_mod_filename(current_package)
5105    };
5106    let mod_source = if current_package.is_empty() {
5107        "the unnamed package".to_owned()
5108    } else {
5109        format!("package {current_package}")
5110    };
5111    output_names.claim(&mod_name, mod_source)?;
5112    out.push(GeneratedFile {
5113        name: mod_name,
5114        package: current_package.to_string(),
5115        kind: GeneratedFileKind::PackageMod,
5116        content: generate_package_mod(
5117            ctx,
5118            current_package,
5119            &sections,
5120            &reg,
5121            &reexport_block,
5122            fds_bytes,
5123            custom_elem_impls,
5124        )?,
5125    });
5126
5127    // Drop the import registry so its bindings can't leak into the next
5128    // package's generation.
5129    ctx.imports_reset();
5130
5131    Ok(())
5132}
5133
5134/// Names occupied at a package's root by real items: top-level messages,
5135/// enums, message nested-types modules, and the `__buffa` sentinel itself.
5136///
5137/// The package root is shared across every `.proto` file in the package, so
5138/// the set is built from *all* of them. File-level extension consts live in
5139/// `__buffa::ext::`, not at the root, so they are re-export *candidates*
5140/// (added by `generate_proto_content`) rather than occupants. Used both to
5141/// filter root re-exports and as the base reserved set for
5142/// `idiomatic_imports` short-name assignment.
5143fn root_occupied_names(
5144    ctx: &context::CodeGenContext,
5145    files: &[&FileDescriptorProto],
5146) -> std::collections::BTreeSet<String> {
5147    let mut occupied = std::collections::BTreeSet::new();
5148    occupied.insert(context::SENTINEL_MOD.to_string());
5149    for file in files {
5150        let package = file.package.as_deref().unwrap_or("");
5151        for m in &file.message_type {
5152            let name = m.name.as_deref().unwrap_or("");
5153            // The declared struct name carries the configured prefix; the
5154            // module name stays proto-derived.
5155            occupied.insert(ctx.config.prefixed_type_name(name));
5156            occupied.insert(ctx.nested_module_name(package, name));
5157        }
5158        for e in &file.enum_type {
5159            occupied.insert(
5160                ctx.config
5161                    .prefixed_type_name(e.name.as_deref().unwrap_or("")),
5162            );
5163        }
5164    }
5165    // The reflect surface is re-exported at the package root directly by
5166    // `generate_package_mod` (not via a `ReexportCandidate`), so candidates
5167    // that could share its names — an extension const named
5168    // `file_descriptor_set_bytes` becomes `FILE_DESCRIPTOR_SET_BYTES` —
5169    // must be filtered against it here or the two `pub use`s collide
5170    // (E0252) in the generated package root.
5171    if ctx.config.generate_reflection {
5172        occupied.insert("descriptor_pool".to_string());
5173        occupied.insert("FILE_DESCRIPTOR_SET_BYTES".to_string());
5174    }
5175    occupied
5176}
5177
5178/// Filter the candidate package-root re-exports against the package's
5179/// existing root namespace and against each other, returning the surviving
5180/// `pub use` lines.
5181///
5182/// The package root is shared across every `.proto` file in the package, so
5183/// the occupied-name set must be built from *all* of them — a top-level
5184/// message named `FooView` declared in `a.proto` would shadow `Foo`'s view
5185/// re-export from `b.proto`.
5186fn surviving_root_reexports(
5187    ctx: &context::CodeGenContext,
5188    files: &[&FileDescriptorProto],
5189    reg: &message::RegistryPaths,
5190    mut candidates: Vec<message::ReexportCandidate>,
5191) -> TokenStream {
5192    use crate::idents::make_field_ident;
5193
5194    let occupied = root_occupied_names(ctx, files);
5195
5196    // `register_types`, when emitted, lives at `__buffa::register_types`.
5197    // `self::` and `#[doc(inline)]` for the same reasons as the view
5198    // re-exports above. Same `any(json, text)` gate as the fn itself.
5199    if ctx.config.emit_register_fn && !reg.is_empty() {
5200        let sentinel = make_field_ident(context::SENTINEL_MOD);
5201        let json_or_text = ctx.config.feature_gates().json_or_text();
5202        candidates.push(message::ReexportCandidate {
5203            name: "register_types".to_string(),
5204            tokens: feature_gates::cfg_block_any(
5205                quote! {
5206                    #[doc(inline)]
5207                    pub use self :: #sentinel :: register_types;
5208                },
5209                &json_or_text,
5210            ),
5211        });
5212    }
5213
5214    message::emit_surviving_reexports(candidates, &occupied)
5215}
5216
5217/// Render the per-package stitcher: owned items at root plus the
5218/// `__buffa::{view,oneof,ext,...}` module wrappers, followed by the
5219/// surviving package-root `pub use` re-exports.
5220fn generate_package_mod(
5221    ctx: &context::CodeGenContext,
5222    current_package: &str,
5223    sections: &PackageSections,
5224    reg: &message::RegistryPaths,
5225    root_reexports: &TokenStream,
5226    fds_bytes: &[u8],
5227    custom_elem_impls: &TokenStream,
5228) -> Result<String, CodeGenError> {
5229    use crate::idents::make_field_ident;
5230
5231    let owned = &sections.owned;
5232    let view = &sections.view;
5233    let lazy_view = &sections.lazy_view;
5234    let view_oneof = &sections.view_oneof;
5235    let oneof = &sections.oneof;
5236    let ext = &sections.ext;
5237
5238    // Each ancillary module is emitted only when its section has
5239    // content. The natural-path re-exports outside `__buffa` target
5240    // these modules — they are emitted only when their target items
5241    // exist, so the conditions align and re-exports never reference
5242    // a missing module.
5243    let view_oneof_mod = if !view_oneof.is_empty() {
5244        quote! {
5245            pub mod oneof {
5246                #[allow(unused_imports)]
5247                use super::*;
5248                #(#view_oneof)*
5249            }
5250        }
5251    } else {
5252        TokenStream::new()
5253    };
5254
5255    // `view_oneof` is only populated for messages that have oneofs, and
5256    // every message also contributes to `view`, so `!view.is_empty()` is
5257    // sufficient — `view_oneof` non-empty implies `view` non-empty.
5258    debug_assert!(view_oneof.is_empty() || !view.is_empty());
5259    let view_mod = if ctx.config.generate_views && !view.is_empty() {
5260        feature_gates::cfg_block(
5261            quote! {
5262                pub mod view {
5263                    #[allow(unused_imports)]
5264                    use super::*;
5265                    #(#view)*
5266                    #view_oneof_mod
5267                }
5268            },
5269            ctx.config.feature_gates().views,
5270        )
5271    } else {
5272        TokenStream::new()
5273    };
5274
5275    // `lazy_view` is only populated when `view` is (the lazy family is
5276    // generated per-message alongside the eager view).
5277    debug_assert!(lazy_view.is_empty() || !view.is_empty());
5278    let lazy_view_mod = if !lazy_view.is_empty() {
5279        feature_gates::cfg_block(
5280            quote! {
5281                pub mod lazy_view {
5282                    #[allow(unused_imports)]
5283                    use super::*;
5284                    #(#lazy_view)*
5285                }
5286            },
5287            ctx.config.feature_gates().views,
5288        )
5289    } else {
5290        TokenStream::new()
5291    };
5292
5293    let oneof_mod = if !oneof.is_empty() {
5294        quote! {
5295            pub mod oneof {
5296                #[allow(unused_imports)]
5297                use super::*;
5298                #(#oneof)*
5299            }
5300        }
5301    } else {
5302        TokenStream::new()
5303    };
5304
5305    let ext_mod = if !ext.is_empty() {
5306        quote! {
5307            pub mod ext {
5308                #[allow(unused_imports)]
5309                use super::*;
5310                #(#ext)*
5311            }
5312        }
5313    } else {
5314        TokenStream::new()
5315    };
5316
5317    let register_fn = if ctx.config.emit_register_fn && !reg.is_empty() {
5318        let gates = ctx.config.feature_gates();
5319        // When the gated consts (`__*_JSON_ANY` / `__*_TEXT_ANY`) are
5320        // `#[cfg(feature = "...")]`, each registration statement that
5321        // references them gets the same gate. `#[cfg]` on a statement is
5322        // allowed; the call disappears with the const.
5323        let json_regs = reg
5324            .json_any
5325            .iter()
5326            .map(|p| {
5327                feature_gates::cfg_block(quote! { reg.register_json_any(super::#p); }, gates.json)
5328            })
5329            .chain(reg.json_ext.iter().map(|p| {
5330                feature_gates::cfg_block(quote! { reg.register_json_ext(super::#p); }, gates.json)
5331            }));
5332        let text_regs = reg
5333            .text_any
5334            .iter()
5335            .map(|p| {
5336                feature_gates::cfg_block(quote! { reg.register_text_any(super::#p); }, gates.text)
5337            })
5338            .chain(reg.text_ext.iter().map(|p| {
5339                feature_gates::cfg_block(quote! { reg.register_text_ext(super::#p); }, gates.text)
5340            }));
5341        // When gating, a feature subset may leave one bucket of statements
5342        // cfg'd out while the other survives — `reg` is still used. But if
5343        // `register_types` itself is gated on `any(json, text)` (below),
5344        // the only reachable bodies have at least one statement, so `reg`
5345        // can't be unused. Keep `#[allow(unused_variables)]` defensively
5346        // anyway: it's harmless, and the alternative — proving the
5347        // invariant holds across future statement-shape changes — is
5348        // brittle.
5349        let allow_unused = if ctx.config.gate_impls_on_crate_features {
5350            quote! { #[allow(unused_variables)] }
5351        } else {
5352            quote! {}
5353        };
5354        // The fn is useless without at least one of the gated modes that
5355        // populate it — and `::buffa::type_registry::TypeRegistry` may
5356        // become feature-gated in the runtime in a future release. Gate the
5357        // fn on `any(...)` of whichever modes are active so it disappears
5358        // alongside the last entry.
5359        feature_gates::cfg_block_any(
5360            quote! {
5361                /// Register this package's `Any` type entries and extension entries.
5362                #allow_unused
5363                pub fn register_types(reg: &mut ::buffa::type_registry::TypeRegistry) {
5364                    #(#json_regs)*
5365                    #(#text_regs)*
5366                }
5367            },
5368            &gates.json_or_text(),
5369        )
5370    } else {
5371        TokenStream::new()
5372    };
5373
5374    // Reflection: embed the FileDescriptorSet bytes and a lazy pool
5375    // accessor so per-message `Reflectable` impls have a descriptor pool to
5376    // resolve against. Lives inside `__buffa` so the impls can reach it via
5377    // a relative `__buffa::reflect::descriptor_pool()` path. Package-root
5378    // `pub use`s re-export `descriptor_pool` and `FILE_DESCRIPTOR_SET_BYTES`
5379    // so consumers don't have to route through the reserved `__buffa`
5380    // sentinel.
5381    let (reflect_mod, reflect_reexport) = if ctx.config.generate_reflection {
5382        let gate = ctx.config.feature_gates().reflect;
5383        // Shared mode: delegate to the single root `__buffa_fds` module
5384        // instead of embedding this package's own byte copy.
5385        let pool_module = if ctx.config.shared_descriptor_pool {
5386            reflect::reflect_pool_module_shared(
5387                current_package,
5388                ctx.config.shared_descriptor_pool_root.as_deref(),
5389            )
5390        } else {
5391            reflect::reflect_pool_module(fds_bytes)
5392        };
5393        (
5394            feature_gates::cfg_block(pool_module, gate),
5395            reflect::reflect_reexports(&quote! { __buffa }, gate),
5396        )
5397    } else {
5398        (TokenStream::new(), TokenStream::new())
5399    };
5400
5401    let sentinel = make_field_ident(context::SENTINEL_MOD);
5402    // The whole `pub mod __buffa { ... }` wrapper is itself omitted
5403    // when none of its inner modules or `register_types` exist.
5404    let buffa_mod = if view_mod.is_empty()
5405        && lazy_view_mod.is_empty()
5406        && oneof_mod.is_empty()
5407        && ext_mod.is_empty()
5408        && register_fn.is_empty()
5409        && reflect_mod.is_empty()
5410        && custom_elem_impls.is_empty()
5411    {
5412        TokenStream::new()
5413    } else {
5414        let allow = allow_lints_attr();
5415        quote! {
5416            #allow
5417            pub mod #sentinel {
5418                #[allow(unused_imports)]
5419                use super::*;
5420                #view_mod
5421                #lazy_view_mod
5422                #oneof_mod
5423                #ext_mod
5424                #register_fn
5425                #reflect_mod
5426                #custom_elem_impls
5427            }
5428        }
5429    };
5430
5431    // Idiomatic imports: the `use` block backing the package-root short
5432    // names (empty unless the registry is in its resolution phase). Only
5433    // ever non-empty in file_per_package mode, where this output is the
5434    // whole single-writer package file.
5435    //
5436    // Load-bearing lint coupling: impl bodies still write fully-qualified
5437    // paths (e.g. `::buffa::MessageField<…>`) for types this block also
5438    // imports — exactly what `unused_qualifications` flags. That lint is
5439    // suppressed by the `ALLOW_LINTS` attr the module-tree wrapper carries,
5440    // so generated files must keep their `#[allow]` wrapper when consumed.
5441    let use_block = ctx.imports_use_block();
5442
5443    let tokens = quote! {
5444        #use_block
5445        #(#owned)*
5446        #buffa_mod
5447        #reflect_reexport
5448        #root_reexports
5449    };
5450
5451    format_tokens(tokens, "")
5452}
5453
5454/// Format a token stream into a generated-file string with the standard
5455/// header comment.
5456fn format_tokens(tokens: TokenStream, source: &str) -> Result<String, CodeGenError> {
5457    let syntax_tree =
5458        syn::parse2::<syn::File>(tokens).map_err(|e| CodeGenError::InvalidSyntax(e.to_string()))?;
5459    let formatted = prettyplease::unparse(&syntax_tree);
5460    let source_line = if source.is_empty() {
5461        String::new()
5462    } else {
5463        format!("// source: {source}\n")
5464    };
5465    Ok(format!("{GENERATED_HEADER}{source_line}\n{formatted}"))
5466}
5467
5468/// Convert a proto package name to its `.mod.rs` stitcher filename.
5469///
5470/// e.g., `"google.protobuf"` → `"google.protobuf.mod.rs"`. The unnamed
5471/// package uses the [`SENTINEL_MOD`](context::SENTINEL_MOD) name as its
5472/// filename stem — `package __buffa;` is already rejected by
5473/// `validate_file`, so the unnamed-package stitcher cannot
5474/// collide with any real package's.
5475pub fn package_to_mod_filename(package: &str) -> String {
5476    if package.is_empty() {
5477        format!("{}.mod.rs", context::SENTINEL_MOD)
5478    } else {
5479        format!("{package}.mod.rs")
5480    }
5481}
5482
5483/// Returns `true` if `package` is covered by any entry in `excludes`.
5484///
5485/// Intended for packages that `include_imports` pulls into
5486/// `file_to_generate` but that a caller does not want emitted — typically
5487/// option-only imports such as `buf.validate` or `gnostic.openapi.v3`, whose
5488/// types are referenced only from custom options and never appear as message
5489/// fields.
5490///
5491/// An exclusion matches a package exactly, or as a dotted-path prefix on a
5492/// component boundary: `"buf.validate"` covers `buf.validate` and
5493/// `buf.validate.foo`, but not `buf.validatex`. Entries are proto package
5494/// paths without a leading dot (`buf.validate`, not `.buf.validate`); an
5495/// empty entry matches only the unnamed package.
5496///
5497/// `generate_with_diagnostics` (which filters `files_to_generate` before
5498/// building the codegen context) and `protoc-gen-reallyme-buffa-packaging` (which
5499/// filters the packages it stitches into `mod.rs`) route their exclusion
5500/// through this one predicate, so the two are guaranteed to drop exactly the
5501/// same set — the invariant the packaging plugin's "Matching a codegen
5502/// plugin's output set" note depends on.
5503pub fn package_is_excluded(package: &str, excludes: &[String]) -> bool {
5504    excludes.iter().any(|ex| {
5505        package == ex
5506            || (package.len() > ex.len()
5507                && package.starts_with(ex.as_str())
5508                && package.as_bytes()[ex.len()] == b'.')
5509    })
5510}
5511
5512/// Normalize and validate one `exclude_package` option value: trim
5513/// whitespace, strip the optional leading dot, reject an empty result or a
5514/// value with empty components (`buf.validate.`, `buf..validate`) — those
5515/// could never match a real package, so a typo would otherwise be a silent
5516/// no-op.
5517///
5518/// The plugin option-string parsers and `generate_with_diagnostics` all run
5519/// entries through this function so normalization cannot drift — the same
5520/// reason they share [`package_is_excluded`].
5521///
5522/// # Errors
5523///
5524/// Returns the user-facing message for a malformed value. The error is a
5525/// plain `String` (not [`CodeGenError`]) deliberately: this is plugin
5526/// option-string parsing, and both plugins' parse layers are
5527/// `Result<_, String>` end to end, surfaced verbatim by protoc.
5528pub fn normalize_exclude_package(value: &str) -> Result<String, String> {
5529    let pkg = value.trim();
5530    let pkg = pkg.strip_prefix('.').unwrap_or(pkg);
5531    if pkg.is_empty() || pkg.split('.').any(str::is_empty) {
5532        return Err(
5533            "'exclude_package' requires a non-empty proto package with no \
5534             empty components, e.g. exclude_package=.buf.validate"
5535                .to_string(),
5536        );
5537    }
5538    Ok(pkg.to_string())
5539}
5540
5541/// Normalize and validate the proto side of one `extern_path` mapping.
5542///
5543/// Trims whitespace, adds the leading dot if absent, drops one trailing dot,
5544/// and rejects a name with an empty segment (`my..common`) or with a segment
5545/// that is not a protobuf identifier (`my.common-name`). Such a name matches
5546/// no type, so a typo would otherwise leave the mapping silently unused.
5547/// `"."`, the catch-all, is returned as is.
5548///
5549/// The `protoc-gen-reallyme-buffa` option parser and `buffa-build` both run entries
5550/// through this function, so the two front ends accept the same names.
5551///
5552/// # Errors
5553///
5554/// Returns the user-facing message for a malformed name, quoting the name as
5555/// given. The error is a plain `String` for the reason
5556/// [`normalize_exclude_package`] gives.
5557pub fn normalize_extern_path_proto_name(value: &str) -> Result<String, String> {
5558    const EXPECTED: &str = "expected '.' or a dotted protobuf package or type name, \
5559                            e.g. .my.pkg or .my.pkg.Type";
5560    let given = value.trim();
5561    if given == "." {
5562        return Ok(given.to_string());
5563    }
5564    let name = given.strip_prefix('.').unwrap_or(given);
5565    let name = name.strip_suffix('.').unwrap_or(name);
5566    for segment in name.split('.') {
5567        if segment.is_empty() {
5568            return Err(format!(
5569                "'extern_path' proto name '{given}' has an empty segment; {EXPECTED}"
5570            ));
5571        }
5572        // protoc's identifier rule: a letter or `_`, then letters, digits or `_`.
5573        let mut chars = segment.chars();
5574        let starts_ok = chars
5575            .next()
5576            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_');
5577        if !(starts_ok && chars.all(|c| c.is_ascii_alphanumeric() || c == '_')) {
5578            return Err(format!(
5579                "'extern_path' proto name '{given}': segment '{segment}' is not a \
5580                 protobuf identifier; {EXPECTED}"
5581            ));
5582        }
5583    }
5584    Ok(format!(".{name}"))
5585}
5586
5587#[cfg(test)]
5588mod extern_path_proto_name_tests {
5589    use super::normalize_extern_path_proto_name as normalize;
5590
5591    #[test]
5592    fn accepts_and_normalizes_valid_names() {
5593        for (given, normalized) in [
5594            (".", "."),
5595            (".my.common", ".my.common"),
5596            ("my.common", ".my.common"),
5597            (".my.common.", ".my.common"),
5598            (" my.v2.Type_1 ", ".my.v2.Type_1"),
5599            ("._internal._Foo", "._internal._Foo"),
5600        ] {
5601            assert_eq!(normalize(given), Ok(normalized.to_string()), "{given:?}");
5602        }
5603    }
5604
5605    #[test]
5606    fn empty_segment_error_quotes_the_name_as_given() {
5607        for given in [
5608            "",
5609            "..",
5610            "..my",
5611            "my..common",
5612            ".my.common..",
5613            ".my.common..Shared",
5614        ] {
5615            let err = normalize(given).unwrap_err();
5616            assert!(
5617                err.contains(&format!("'{given}' has an empty segment")),
5618                "{given:?}: {err}"
5619            );
5620        }
5621    }
5622
5623    #[test]
5624    fn invalid_identifier_error_names_the_segment() {
5625        for (given, segment) in [
5626            ("my.123", "123"),
5627            (".my.common-name.", "common-name"),
5628            ("my.com mon", "com mon"),
5629        ] {
5630            let err = normalize(given).unwrap_err();
5631            assert!(
5632                err.contains(&format!("proto name '{given}': segment '{segment}'")),
5633                "{given:?}: {err}"
5634            );
5635        }
5636    }
5637}
5638
5639#[cfg(test)]
5640mod package_exclusion_tests {
5641    use super::package_is_excluded;
5642
5643    fn ex(list: &[&str]) -> Vec<String> {
5644        list.iter().map(|s| s.to_string()).collect()
5645    }
5646
5647    #[test]
5648    fn exact_match_is_excluded() {
5649        assert!(package_is_excluded("buf.validate", &ex(&["buf.validate"])));
5650    }
5651
5652    #[test]
5653    fn subpackage_matches_on_component_boundary() {
5654        assert!(package_is_excluded("gnostic.openapi.v3", &ex(&["gnostic"])));
5655        assert!(package_is_excluded(
5656            "buf.validate.priv",
5657            &ex(&["buf.validate"])
5658        ));
5659    }
5660
5661    #[test]
5662    fn prefix_without_boundary_does_not_match() {
5663        assert!(!package_is_excluded(
5664            "buf.validatex",
5665            &ex(&["buf.validate"])
5666        ));
5667        assert!(!package_is_excluded("gnostics", &ex(&["gnostic"])));
5668    }
5669
5670    #[test]
5671    fn unrelated_package_is_kept() {
5672        assert!(!package_is_excluded(
5673            "example.user.v1",
5674            &ex(&["buf.validate", "gnostic"])
5675        ));
5676    }
5677
5678    #[test]
5679    fn empty_exclude_list_keeps_everything() {
5680        assert!(!package_is_excluded("buf.validate", &ex(&[])));
5681    }
5682
5683    // An empty exclude entry is unreachable through either plugin
5684    // (`normalize_exclude_package` rejects it); this pins the raw
5685    // predicate's documented behavior for direct callers.
5686    #[test]
5687    fn empty_entry_matches_only_the_unnamed_package() {
5688        assert!(package_is_excluded("", &ex(&[""])));
5689        assert!(!package_is_excluded("foo", &ex(&[""])));
5690    }
5691
5692    #[test]
5693    fn normalize_strips_dot_and_rejects_malformed() {
5694        use super::normalize_exclude_package;
5695        assert_eq!(
5696            normalize_exclude_package(".buf.validate").as_deref(),
5697            Ok("buf.validate")
5698        );
5699        assert_eq!(
5700            normalize_exclude_package("gnostic").as_deref(),
5701            Ok("gnostic")
5702        );
5703        assert!(normalize_exclude_package("").is_err());
5704        assert!(normalize_exclude_package(".").is_err());
5705        assert!(normalize_exclude_package("  ").is_err());
5706        // Entries that could never match a real package are rejected, not
5707        // silently accepted as no-ops.
5708        assert!(normalize_exclude_package("buf.validate.").is_err());
5709        assert!(normalize_exclude_package("buf..validate").is_err());
5710    }
5711}
5712
5713/// Convert a proto package name to its [`file_per_package`] output filename.
5714///
5715/// e.g., `"google.protobuf"` → `"google.protobuf.rs"`. The unnamed
5716/// package uses [`SENTINEL_MOD`](context::SENTINEL_MOD) — same
5717/// collision-avoidance as [`package_to_mod_filename`].
5718///
5719/// [`file_per_package`]: CodeGenConfig::file_per_package
5720pub fn package_to_filename(package: &str) -> String {
5721    if package.is_empty() {
5722        format!("{}.rs", context::SENTINEL_MOD)
5723    } else {
5724        format!("{package}.rs")
5725    }
5726}
5727
5728/// Convert a `.proto` file path to its content-file stem.
5729///
5730/// e.g., `"google/protobuf/timestamp.proto"` → `"google.protobuf.timestamp"`.
5731/// Content files append `""`, `".__view"`, `".__oneof"`,
5732/// `".__view_oneof"`, or `".__ext"` plus `".rs"` — emitted only for
5733/// kinds with non-empty content.
5734pub fn proto_path_to_stem(proto_path: &str) -> String {
5735    let without_ext = proto_path.strip_suffix(".proto").unwrap_or(proto_path);
5736    without_ext.replace('/', ".")
5737}
5738
5739/// Merge downstream [`Companion`](GeneratedFileKind::Companion) files into
5740/// the per-package stitcher produced by [`generate`].
5741///
5742/// For each companion file this function locates the
5743/// [`PackageMod`](GeneratedFileKind::PackageMod) entry in `files` with a
5744/// matching package and appends `include!("<name>");` at file scope after
5745/// buffa's own output — at package root, alongside the owned message types,
5746/// not under `__buffa::`. The companion files themselves are appended to
5747/// `files` so that build integrations can write everything to disk in one
5748/// pass.
5749///
5750/// **Call this once per build**; it does not deduplicate, so a second call
5751/// with the same companions emits a second `include!` for each, which fails
5752/// to compile downstream with a duplicate-definition error.
5753///
5754/// `name` must be a bare-sibling filename — the same convention buffa uses
5755/// for its own `include!` calls, so it resolves relative to the stitcher
5756/// without any `OUT_DIR` prefix. Names must not contain `/` or `\`, must not
5757/// be empty, `.` or `..`, and must not collide with any of buffa's own
5758/// generated filenames for the same package (`<stem>.rs`, `<stem>.__view.rs`,
5759/// etc.) — pick an unused suffix such as `<stem>.__myplugin.rs`. The name is
5760/// written into the `include!` as an escaped string literal, as buffa's own
5761/// include paths are.
5762///
5763/// Companion files with no matching `PackageMod` (e.g. for a package buffa
5764/// did not generate any output for) are still appended to `files` but no
5765/// `include!` is emitted; the caller is responsible for wiring them up. If
5766/// you don't expect orphans, check that every companion's `package` appears
5767/// in `files` as a `PackageMod` after calling.
5768///
5769/// # Panics
5770///
5771/// Panics if a companion's `name` contains `/` or `\`, or is empty, `.` or
5772/// `..`. Every name is checked before `files` is changed.
5773#[track_caller]
5774pub fn apply_companions(files: &mut Vec<GeneratedFile>, companions: Vec<GeneratedFile>) {
5775    for comp in &companions {
5776        assert!(
5777            !comp.name.contains(['/', '\\']),
5778            "companion file name {:?} contains a path separator ('/' or '\\'); use a \
5779             bare file name such as `<stem>.__myplugin.rs`, which include!() resolves \
5780             next to the stitcher",
5781            comp.name
5782        );
5783        assert!(
5784            !matches!(comp.name.as_str(), "" | "." | ".."),
5785            "companion file name {:?} is empty, `.` or `..`, which names a directory, \
5786             not a file; use a bare file name such as `<stem>.__myplugin.rs`",
5787            comp.name
5788        );
5789    }
5790    for comp in &companions {
5791        if let Some(pkg_mod) = files
5792            .iter_mut()
5793            .find(|f| f.kind == GeneratedFileKind::PackageMod && f.package == comp.package)
5794        {
5795            pkg_mod
5796                .content
5797                .push_str(&format!("include!({:?});\n", comp.name));
5798        }
5799    }
5800    files.extend(companions);
5801}
5802
5803/// Why a selected message cannot use recursive cleanup.
5804#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
5805#[non_exhaustive]
5806pub enum ZeroizeConfigurationErrorReason {
5807    /// Ordinary reflection would copy a guarded descendant into a dynamic snapshot.
5808    #[error(
5809        "containing messages need cleanup too so reflection cannot snapshot a guarded descendant"
5810    )]
5811    ReflectionParent,
5812    /// Unknown payload storage is not a wipe owner.
5813    #[error("requires unknown_fields=false")]
5814    UnknownFieldStorage,
5815    /// Strict UTF-8 mapping cannot select a custom raw map key.
5816    #[error("raw byte map keys under strict_utf8_mapping cannot use guarded representations")]
5817    RawMapKey,
5818    /// A buffer still has its ordinary representation.
5819    #[error("every bytes/string slot requires a custom Zeroize + ZeroizeOnDrop representation")]
5820    BufferRepresentation,
5821    /// A guarded representation could use default JSON decoding.
5822    #[error(
5823        "requires json_policy_type for each custom bytes/string representation when json=true"
5824    )]
5825    JsonPolicy,
5826}
5827
5828/// Code generation error.
5829#[derive(Debug, Clone, thiserror::Error)]
5830#[non_exhaustive]
5831pub enum CodeGenError {
5832    /// A view-export restriction matches no known message.
5833    #[error("deny_view_json rule '{rule}' matches no known message")]
5834    ViewJsonRuleMatchedNothing { rule: String },
5835    /// A cleanup selector matches no message in the request's descriptors.
5836    #[error("zeroize_in rule '{rule}' matches no known message")]
5837    ZeroizeRuleMatchedNothing { rule: String },
5838
5839    /// A listed policy type is not selected by any unshadowed representation rule.
5840    #[error("json_policy_type '{rust_type}' is not selected by any unshadowed bytes/string rule; match the representation type spelling exactly")]
5841    JsonPolicyTypeMatchedNothing { rust_type: String },
5842    /// A representation has the same final type name as a listed policy, but a different spelling.
5843    #[error("representation type '{selected}' has the same name as json_policy_type '{listed}', but a different spelling; list the exact type or correct the representation rule")]
5844    JsonPolicyTypeNearMiss { selected: String, listed: String },
5845
5846    /// A selected message cannot satisfy the recursive cleanup contract.
5847    #[error("zeroize message '{message}': {reason}")]
5848    InvalidZeroizeConfiguration {
5849        /// Protobuf message name from the schema.
5850        message: String,
5851        /// A fixed, typed configuration reason.
5852        reason: ZeroizeConfigurationErrorReason,
5853    },
5854
5855    /// A required field was absent in a descriptor, or a message or enum name
5856    /// was empty.
5857    ///
5858    /// The string is the descriptor field, such as `message.name` or
5859    /// `field.type_name`.
5860    #[error("missing required descriptor field: {0}")]
5861    MissingField(&'static str),
5862    /// A resolved type path string could not be parsed as a Rust type.
5863    #[error("invalid Rust type path: '{0}'")]
5864    InvalidTypePath(String),
5865    /// A [`json_policy_types`](CodeGenConfig::json_policy_types) `string`
5866    /// type is the key type of an enum-valued `map`. Policy keys do not yet
5867    /// support the enum map helpers' unknown-value filtering. The string is
5868    /// the map field's proto path.
5869    #[error(
5870        "enum-valued map field '{0}' has a json_policy_type string key; \
5871         policy keys do not support enum map filtering, so select another key representation"
5872    )]
5873    JsonPolicyMapKey(String),
5874    /// A `box_type_custom` pointer template did not contain the `*` placeholder.
5875    ///
5876    /// The custom pointer wraps the message type, so the template must mark where
5877    /// it goes with `*`, e.g. `"::smallbox::SmallBox<*, smallbox::space::S4>"`.
5878    #[error("box_type template must contain a `*` placeholder for the message type: '{0}'")]
5879    MissingWildcard(String),
5880    /// A `repeated_type_custom` collection template did not contain the `*`
5881    /// element placeholder.
5882    ///
5883    /// Unlike the scalar `string_type_custom` / `bytes_type_custom` knobs (which
5884    /// take a complete type path), a collection template wraps the element type
5885    /// and must mark where it goes with `*`, e.g. `"::my_crate::SmallList<*>"`.
5886    #[error("repeated_type template must contain a `*` element placeholder: '{0}'")]
5887    MissingListPlaceholder(String),
5888    /// The accumulated `TokenStream` failed to parse as valid Rust syntax.
5889    #[error("generated code failed to parse as Rust: {0}")]
5890    InvalidSyntax(String),
5891    /// A requested file was not present in the descriptor set.
5892    #[error("file_to_generate '{0}' not found in descriptor set")]
5893    FileNotFound(String),
5894    /// Two generated files would be written to the same output path. A
5895    /// content file is named after its `.proto` path with `/` replaced by
5896    /// `.`, so `foo/bar.proto` and `foo.bar.proto` both produce `foo.bar.rs`;
5897    /// a package's module file is `<package>.mod.rs`, which is also the
5898    /// content file of `foo/mod.proto` in package `foo`.
5899    ///
5900    /// Resolve by renaming a proto file (the only one involved, when the
5901    /// other source is a package), or by setting
5902    /// [`CodeGenConfig::file_per_package`], which emits one file per package
5903    /// and no per-proto content files.
5904    #[error(
5905        "output file name conflict: {first_source} and {second_source} both \
5906         generate '{file_name}'; rename a proto file so that the output names \
5907         differ, or enable file_per_package"
5908    )]
5909    OutputFileNameConflict {
5910        /// The output path that both inputs map to.
5911        file_name: String,
5912        /// The input that generated the path first: the `.proto` file path
5913        /// as its descriptor names it for a content file, or
5914        /// `package <name>` (`the unnamed package` for a file that declares
5915        /// no package) for a package's module file.
5916        first_source: String,
5917        /// The input that generated the path second, in the same form as
5918        /// `first_source`.
5919        second_source: String,
5920    },
5921    /// Unexpected descriptor state (e.g. a map entry or oneof that cannot be
5922    /// resolved to a known descriptor field).
5923    #[error("codegen error: {0}")]
5924    Other(String),
5925    /// A proto field name uses the `__buffa_` reserved prefix, which would
5926    /// conflict with buffa's internal generated fields.
5927    #[error(
5928        "reserved field name '{field_name}' in message '{message_name}': \
5929             proto field names starting with '__buffa_' conflict with buffa's \
5930             internal fields"
5931    )]
5932    ReservedFieldName {
5933        message_name: String,
5934        field_name: String,
5935    },
5936    /// Two sibling messages produce the same Rust module name after
5937    /// snake_case conversion (e.g., `HTTPRequest` and `HttpRequest` both
5938    /// become `pub mod http_request`).
5939    #[error(
5940        "module name conflict in '{scope}': messages '{name_a}' and '{name_b}' \
5941         both produce module '{module_name}'"
5942    )]
5943    ModuleNameConflict {
5944        scope: String,
5945        name_a: String,
5946        name_b: String,
5947        module_name: String,
5948    },
5949    /// Two oneofs of one message produce the same Rust enum name after
5950    /// PascalCase conversion and keyword escaping (e.g., `foo_bar` and
5951    /// `foo__bar` both become `FooBar`; `self` and `self_` both become
5952    /// `Self_`). Resolve by renaming one of the oneofs. A oneof's name is in
5953    /// neither the wire format nor JSON, so the rename changes generated
5954    /// code only.
5955    #[error(
5956        "oneof enum name conflict in message '{message_name}': oneofs \
5957         '{first_oneof}' and '{second_oneof}' both map to Rust enum '{rust_name}'; \
5958         rename one of them"
5959    )]
5960    OneofEnumNameConflict {
5961        /// Fully-qualified proto name of the message, without a leading dot.
5962        message_name: String,
5963        /// Proto name of the oneof declared first.
5964        first_oneof: String,
5965        /// Proto name of the oneof declared second.
5966        second_oneof: String,
5967        /// The Rust enum name that both oneofs map to.
5968        rust_name: String,
5969    },
5970    /// Two members of one oneof produce the same Rust variant name after
5971    /// PascalCase conversion and keyword escaping (e.g., `foo` and `foo_`
5972    /// both become `Foo`; `foo_bar` and `foo__bar` both become `FooBar`;
5973    /// `self` and `self_` both become `Self_`). Resolve by renaming one of
5974    /// the members. A member's name is its default JSON and text-format
5975    /// name, so the rename changes those too unless the field sets a
5976    /// `json_name`; the wire format is unaffected.
5977    #[error(
5978        "oneof variant name conflict in message '{message_name}': members \
5979         '{first_field}' and '{second_field}' of oneof '{oneof_name}' both map \
5980         to Rust variant '{rust_name}'; rename one of them"
5981    )]
5982    OneofVariantNameConflict {
5983        /// Fully-qualified proto name of the message, without a leading dot.
5984        message_name: String,
5985        /// Proto name of the oneof that declares both members.
5986        oneof_name: String,
5987        /// Proto name of the member declared first.
5988        first_field: String,
5989        /// Proto name of the member declared second.
5990        second_field: String,
5991        /// The Rust variant name that both members map to.
5992        rust_name: String,
5993    },
5994    /// Two types, each a message or an enum, declared at package level in
5995    /// one package or nested in one message, produce the same Rust type
5996    /// name. With an empty [`CodeGenConfig::type_name_prefix`], a type named
5997    /// after a Rust keyword (`type`, `Self`), or after a primitive type that
5998    /// generated code uses (`bool`, `str`, `u8`, `usize`, `i32`, `i64`,
5999    /// `u32`, `u64`, `f32`, `f64`), is generated with a trailing `_`, so
6000    /// `bool` and `bool_` both become `bool_`.
6001    ///
6002    /// Resolve by renaming one of the types, which changes its full name and
6003    /// its `Any` type URL, or by setting a prefix: with prefix `Pb` the two
6004    /// types are `Pbbool` and `Pbbool_`.
6005    #[error(
6006        "type name conflict in '{scope}': '{first_type}' and '{second_type}' \
6007         both map to Rust type '{rust_name}'; rename one of them"
6008    )]
6009    TypeNameConflict {
6010        /// Fully-qualified proto name of the package or message that
6011        /// declares both types, without a leading dot. Empty for a
6012        /// package-level conflict in a file that declares no package.
6013        scope: String,
6014        /// Proto simple name of the type visited first: within each file,
6015        /// messages in declaration order, then enums.
6016        first_type: String,
6017        /// Proto simple name of the type visited second.
6018        second_type: String,
6019        /// The Rust type name that both map to.
6020        rust_name: String,
6021    },
6022    /// A proto package segment, message name, or file-level enum name
6023    /// would emit a Rust item matching the reserved sentinel `__buffa`.
6024    ///
6025    /// This is the only name buffa reserves in user namespace. Resolve by
6026    /// renaming the proto element.
6027    #[error(
6028        "reserved name '{name}' at {location}: this name is reserved for \
6029         buffa's generated ancillary types (views, oneof enums, \
6030         extensions). Rename the proto element."
6031    )]
6032    ReservedModuleName { name: String, location: String },
6033    /// [`CodeGenConfig::shared_corpus_context`] was built from a different
6034    /// corpus or different oneof/pointer-repr rules than this call's.
6035    ///
6036    /// `what` names the mismatch: `"files"`, `"unboxed_oneof_fields"`, or
6037    /// `"pointer_fields"`. Build the context with
6038    /// [`SharedCorpusContext::new`] from the same `files` and config as every
6039    /// `generate()` call that uses it.
6040    #[error(
6041        "shared_corpus_context was built from different {what} than this \
6042         generate() call; build it from the same files and oneof/pointer-repr \
6043         config as every call that uses it"
6044    )]
6045    SharedCorpusContextMismatch { what: &'static str },
6046    /// The input contains a message with `option message_set_wire_format = true`
6047    /// but [`CodeGenConfig::allow_message_set`] was not set.
6048    #[error(
6049        "message '{message_name}' uses `option message_set_wire_format = true` \
6050         but CodeGenConfig::allow_message_set is false; MessageSet is a legacy \
6051         wire format — set allow_message_set(true) if this is intentional"
6052    )]
6053    MessageSetNotSupported { message_name: String },
6054    /// A custom attribute string configured via [`CodeGenConfig::type_attributes`],
6055    /// [`CodeGenConfig::field_attributes`], [`CodeGenConfig::message_attributes`],
6056    /// [`CodeGenConfig::enum_attributes`], [`CodeGenConfig::oneof_attributes`],
6057    /// or [`CodeGenConfig::oneof_struct_field_attributes`] is not one or more
6058    /// outer `#[...]` attributes. An empty string, an inner attribute
6059    /// `#![...]` and a string with any token outside an attribute are all
6060    /// rejected, whether or not the rule's path matches a generated item.
6061    #[error(
6062        "invalid custom attribute for path '{path}': '{attribute}' must be one or \
6063         more outer `#[...]` attributes ({detail})"
6064    )]
6065    InvalidCustomAttribute {
6066        path: String,
6067        attribute: String,
6068        detail: String,
6069    },
6070    /// [`CodeGenConfig::type_name_prefix`] is not PascalCase
6071    /// (`[A-Z][A-Za-z0-9]*`), so prepending it to a type name would produce
6072    /// an invalid or unconventionally-cased Rust identifier.
6073    #[error(
6074        "invalid type_name_prefix '{prefix}': must be empty or PascalCase \
6075         (start with an ASCII uppercase letter, followed by ASCII letters \
6076         and digits only)"
6077    )]
6078    InvalidTypeNamePrefix { prefix: String },
6079    /// Two fields of one message, in a file being generated, have the same
6080    /// field number. protoc rejects such a message, so the descriptor was
6081    /// built in code or changed after protoc wrote it.
6082    ///
6083    /// Generated code for it would write both fields with one field number
6084    /// and decode every record with that number into one of them, so the
6085    /// error is returned whichever codec is selected.
6086    #[error(
6087        "duplicate field number in message '{message_name}': fields '{first_field}' and \
6088         '{second_field}' are both numbered {number}; protoc rejects this, so renumber one of \
6089         them in the code or tool that built the descriptor"
6090    )]
6091    DuplicateFieldNumber {
6092        /// The message's full name, without a leading dot.
6093        message_name: String,
6094        /// The name of the field declared first.
6095        first_field: String,
6096        /// The name of the field declared second.
6097        second_field: String,
6098        /// The number both fields have, as the descriptor gives it. It may be
6099        /// outside the valid range for a field number.
6100        number: i32,
6101    },
6102}
6103
6104#[cfg(test)]
6105mod tests;
6106
6107mod guarded_arbitrary;
6108mod inspect;
6109mod sensitive;