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