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