Skip to main content

CodeGenConfig

Struct CodeGenConfig 

Source
#[non_exhaustive]
pub struct CodeGenConfig {
Show 51 fields pub generate_zeroize: bool, pub zeroize_messages: Vec<String>, pub deny_view_json: Vec<String>, pub allow_unmatched_message_rules: bool, pub generate_views: bool, pub lazy_views: bool, pub preserve_unknown_fields: bool, pub preserve_unknown_fields_in: Vec<(String, bool)>, pub deny_unknown_json_fields: bool, pub deny_unknown_json_fields_in: Vec<(String, bool)>, pub generate_json: bool, pub generate_arbitrary: bool, pub skip_debug: Vec<String>, pub extern_paths: Vec<(String, String)>, pub bytes_fields: Vec<(String, BytesRepr)>, pub string_fields: Vec<(String, StringRepr)>, pub json_policy_types: Vec<String>, pub emit_custom_type_impls: bool, pub map_fields: Vec<(String, MapRepr)>, pub pointer_fields: Vec<(String, PointerRepr)>, pub repeated_fields: Vec<(String, RepeatedRepr)>, pub feature_overrides: Vec<(String, FeatureOverride)>, pub unboxed_oneof_fields: Vec<String>, pub strict_utf8_mapping: bool, pub allow_message_set: bool, pub generate_text: bool, pub emit_register_fn: bool, pub file_per_package: bool, pub type_attributes: Vec<(String, String)>, pub field_attributes: Vec<(String, String)>, pub message_attributes: Vec<(String, String)>, pub enum_attributes: Vec<(String, String)>, pub oneof_attributes: Vec<(String, String)>, pub oneof_struct_field_attributes: Vec<(String, String)>, pub gate_impls_on_crate_features: bool, pub generate_with_setters: bool, pub map_entries_omit_defaults: bool, pub generate_reflection: bool, pub generate_reflection_vtable: bool, pub shared_descriptor_pool: bool, pub shared_descriptor_pool_root: Option<String>, pub shared_corpus_context: Option<SharedCorpusContext>, pub gate_reflect_on_crate_feature: bool, pub idiomatic_enum_aliases: bool, pub idiomatic_imports: bool, pub idiomatic_field_names: bool, pub feature_gate_names: FeatureGateNames, pub type_name_prefix: String, pub exclude_packages: Vec<String>, pub codec_strategy: CodecStrategy, pub codec_strategy_in: Vec<(String, CodecStrategy)>,
}
Expand description

Configuration for code generation.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§generate_zeroize: bool

Generate recursive Zeroize, ZeroizeOnDrop and Drop for messages, oneofs and the owned storage of their views. Borrowed input is not wiped. Requires the runtime’s zeroize feature, guarded custom bytes/string representations, and unknown-field storage disabled. Collections default to wipe-owning runtime collections; referenced messages must also support cleanup. Reflection uses borrowed InspectMessage access without snapshots. Arbitrary construction uses an early cleanup owner and a depth bound.

§zeroize_messages: Vec<String>

Proto path prefixes selecting messages for recursive cleanup. . selects every generated message, including nested messages.

§deny_view_json: Vec<String>

Message prefixes whose views reject JSON serialization before writing output. The restriction propagates to containing messages, including through maps and imported descriptors. Owned-message JSON is unchanged. . selects all. Every rule must match a known message, including imported messages.

§allow_unmatched_message_rules: bool

Permit message selectors that belong to another directory-scoped plugin request. Such selectors still produce warnings. Keep this disabled when validating the complete project so misspelled security rules are errors.

§generate_views: bool

Whether to generate borrowed view types (MyMessageView<'a>) in addition to owned types.

§lazy_views: bool

Whether to additionally generate the lazy view family (MyMessageLazyView<'a>) alongside the eager views (default: false).

Lazy views implement buffa::LazyMessageView: decode_lazy performs a single non-recursive scan, recording singular/repeated message fields as undecoded byte ranges (LazyMessageFieldView / LazyRepeatedView) that decode on access — reading a few fields of many sub-messages no longer allocates or recurses into untouched sub-trees. The eager MyMessageView family is unchanged (output is byte-identical with or without this flag), so eager and lazy views coexist and generic MessageView consumers never silently inherit deferred validation.

Semantics of the lazy family:

  • Eager carve-outs: groups / editions DELIMITED fields (no length prefix to defer), oneof message variants, and map message values use the eager view types.
  • Merge preserved: a singular message field split across wire occurrences is recorded as fragments and merged on access.
  • Budgets flow: the recursion depth, unknown-field allowance, and element-memory budget remaining at each deferred field are recorded and replayed per access (a per-subtree approximation of the shared budgets).
  • Deferred validation: malformed deferred bytes error on access, from the fallible to_owned_message, and as a serde error from the view Serialize impl. ViewEncode replays recorded fragments without validating them.
  • No ReflectMessage, OwnedView, or text-format surface — use the eager family for those.

Requires generate_views (the lazy family reuses the eager view-oneof enums and eager sub-view types); with views disabled the flag is ignored with a warning.

§preserve_unknown_fields: bool

Whether to preserve unknown fields (default: true).

Path-scoped overrides go in preserve_unknown_fields_in; the last matching rule wins over this global default.

A message with preservation off has no __buffa_unknown_fields field, and with it loses everything built on that field: its ExtensionSet impl (typed extension access), ReflectMessage::unknown_fields, extension round-tripping through textproto, and [ext] keys in JSON.

§preserve_unknown_fields_in: Vec<(String, bool)>

Path-scoped overrides for preserve_unknown_fields. Each entry is (proto_path_prefix, enabled), with a leading dot (".pkg.Msg").

Matching uses the same proto-segment-aware prefix rules as bytes_fields and unboxed_oneof_fields: a rule covers the message it names and every message nested inside it, and "." covers everything. A rule naming a nested message does not cover its enclosing message. The last matching rule wins, so a later, more specific entry can carve a nested message back out of an earlier, broader one. Granularity is per-message: the flag gates whether the struct carries __buffa_unknown_fields. Preservation is a property of each message type, not of a value graph, so a preserved message’s sub-messages keep their own unknown fields only if their types are covered too.

A rule that matches no generated message produces a CodeGenWarning::PreserveUnknownFieldsRuleMatchedNothing.

§deny_unknown_json_fields: bool

Whether generated JSON deserializers reject unknown fields (default: false, lenient).

Path-scoped overrides go in deny_unknown_json_fields_in; the last matching rule wins over this global default. With generate_json off the setting changes nothing and produces a CodeGenWarning::DenyUnknownJsonFieldsRequiresJson.

A strict message rejects every key that matches none of its fields, under either the JSON name or the proto name, with serde’s unknown_field error. "[pkg.ext]" keys of a message that has extension ranges and preserves unknown fields still go through the extension registry, where JsonParseOptions::strict_extension_keys governs unregistered ones. A message with extension ranges and preservation off rejects them like any other unknown key.

§deny_unknown_json_fields_in: Vec<(String, bool)>

Path-scoped overrides for deny_unknown_json_fields. Each entry is (proto_path_prefix, enabled), with a leading dot (".pkg.Msg").

Matching uses the same proto-segment-aware prefix rules as preserve_unknown_fields_in: a rule covers the message it names and every message nested inside it, "." covers everything, and the last matching rule wins, so a later, more specific entry can carve a nested message back out of an earlier, broader one.

A rule that matches no generated message produces a CodeGenWarning::DenyUnknownJsonFieldsRuleMatchedNothing.

§generate_json: bool

Whether to derive serde::Serialize / serde::Deserialize on generated message structs and enum types, and emit #[serde(with = "...")] attributes for proto3 JSON’s special scalar encodings (int64 as quoted string, bytes as base64, etc.).

When this is true, the downstream crate must depend on serde and must enable the buffa/json feature for the runtime helpers.

Oneof fields use #[serde(flatten)] with custom Serialize / Deserialize impls so that each variant appears as a top-level JSON field (proto3 JSON inline oneof encoding).

§generate_arbitrary: bool

Whether to emit #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] on generated message structs and enum types. An enum with a [deprecated = true] variant gets a generated impl under the same cfg instead, because the derive would warn on that variant.

When this is true, the downstream crate must add arbitrary as an optional dependency and enable the buffa/arbitrary feature. The downstream crate’s Cargo feature that gates arbitrary must be named exactly "arbitrary" — the generated cfg_attr uses that literal string and cannot be customized. This applies to both the struct-level derive(Arbitrary) and the per-field #[arbitrary(with = ...)] attributes described below.

For a field whose bytes_fields or string_fields rule selects a non-default type, codegen emits #[arbitrary(with = ...)] using helpers in ::buffa::__private, so the substituted type needs no Arbitrary impl. This covers singular, optional, repeated and oneof fields, and the key and value of a map field.

§skip_debug: Vec<String>

Proto paths of the messages and enums whose generated Debug implementation is omitted, so that the consuming crate can write its own.

For messages a rule is a proto-segment-aware prefix: ".pkg.Msg" matches that message and the messages nested inside it, ".pkg" matches every message in the package and its sub-packages, and "." matches every message. The oneof enums of a matched message lose their Debug with it. An enum loses its Debug only when a rule is its exact name, such as ".pkg.Level". View types keep theirs.

A matched enum does not compile until the crate implements Debug for it, because buffa::Enumeration requires Debug. A matched message needs an impl when an unmatched message or oneof holds it, because their generated Debug formats it, and whenever reflection is generated, because ReflectElement requires Debug.

A rule that matches no generated message and names no generated enum produces CodeGenWarning::SkipDebugRuleMatchedNothing.

§extern_paths: Vec<(String, String)>

External type path mappings.

Each entry maps either a fully-qualified protobuf package prefix (e.g., ".my.common") to a Rust module path (e.g., "::common_protos"), or a single type FQN (e.g., ".my.common.Shared") to a full Rust type path (e.g., "::shared_types::Shared"). Matched types reference the extern Rust path instead of being generated, allowing shared proto packages to be compiled once in a dedicated crate and referenced from others. An exact type-FQN entry wins over a covering package prefix; otherwise the longest matching prefix wins.

The proto side must be "." (every type) or a fully-qualified name: a leading dot, then protobuf identifiers separated by single dots, with no trailing dot. generate does not validate entries, and an entry in another form matches no type; a caller that fills this field directly should pass each name through normalize_extern_path_proto_name, as protoc-gen-reallyme-buffa and buffa-build do.

Well-known types (google.protobuf.*) are automatically mapped to ::buffa_types::google::protobuf::* without needing an explicit entry here. To override with a custom implementation, add an extern_path for .google.protobuf pointing to your crate.

When JSON generation is enabled, an external message routed through a ProtoJSON container helper must implement buffa::json_helpers::ProtoElemJson so generated containers can apply ProtoJSON encoding and reject null elements/values. This includes external wrapper types in repeated/map fields and external message values in bytes-keyed maps; ordinary message containers use serde directly.

§bytes_fields: Vec<(String, BytesRepr)>

Ordered (proto-path-prefix, BytesRepr) rules selecting the Rust type for bytes fields. Later rules win, so a broad rule (e.g. "." → Bytes) can be refined by a more specific one. Fields matching no rule use Vec<u8>.

A rule is a prefix of a fully-qualified field path, matched on whole path segments, and starts with a dot: ".my.pkg.Msg.data", ".my.pkg.Msg", ".my.pkg", or "." for every field. Codegen does not add the dot (buffa-build does), and a path without it matches no field. A rule that does not match a field of a generated message produces CodeGenWarning::FieldTypeRuleMatchedNothing.

§string_fields: Vec<(String, StringRepr)>

Ordered (proto-path-prefix, StringRepr) rules selecting the Rust type for string fields. Later rules win, so a broad rule (e.g. "." → SmolStr) can be refined by a more specific one (".my.pkg.Msg.field" → CompactString). Fields matching no rule use String. The path is matched with the same proto-segment-aware prefix logic as bytes_fields.

Applies to singular, optional, and repeated string fields, oneof string variants, and the string keys and values of map fields (matched by the map field’s path). A rule that does not match a field of a generated message produces CodeGenWarning::FieldTypeRuleMatchedNothing.

§json_policy_types: Vec<String>

Custom bytes and string representations, named by Rust type path exactly as in their BytesRepr::Custom / StringRepr::Custom rules, whose protobuf JSON goes through buffa::json_helpers::ProtoBytesJson or ProtoStringJson.

Every field of a listed type then serializes and deserializes through the type’s policy: singular, optional, repeated and oneof fields, map values, and the corresponding fields of generated views and owned views. Paths are compared as parsed Rust types, so whitespace does not matter. A listed type that no unshadowed representation rule names produces CodeGenError::JsonPolicyTypeMatchedNothing; a listed string type used as a key of an enum-valued map is a CodeGenError::JsonPolicyMapKey. Unlisted custom types keep their existing JSON behavior.

§emit_custom_type_impls: bool

Emit element JSON/reflection impls for custom bytes/string types.

Disable this when the representation’s defining crate already supplies ProtoElemJson, ReflectElement, ReflectMapKey and InspectElement as needed. This permits shared foreign representations and separate generation calls without violating coherence or emitting duplicate implementations. Missing implementations remain compile errors in the generated code.

§map_fields: Vec<(String, MapRepr)>

Ordered (proto-path-prefix, MapRepr) rules selecting the owned Rust map collection for map fields. Later rules win, with the same proto-segment-aware prefix matching as bytes_fields ("." matches every field). Fields matching no rule use HashMap<K, V>.

Independent of the element/value representation: a map field’s key and value types are chosen by the usual scalar/string/bytes/message rules, and this option changes only the surrounding collection. A rule that does not match a field of a generated message produces CodeGenWarning::FieldTypeRuleMatchedNothing.

§pointer_fields: Vec<(String, PointerRepr)>

Ordered (proto-path-prefix, PointerRepr) rules selecting the owned smart pointer for singular message fields (the pointer inside MessageField<T>). Later rules win, same proto-segment-aware prefix matching as bytes_fields. Fields matching no rule use Box<T>.

Applies to singular (and proto2 optional/required) message fields only — not repeated message fields (a collection) or oneof message variants.

§repeated_fields: Vec<(String, RepeatedRepr)>

Ordered (proto-path-prefix, RepeatedRepr) rules selecting the owned Rust collection for repeated fields. Later rules win, with the same proto-segment-aware prefix matching as bytes_fields ("." matches every field). Fields matching no rule use Vec<T>.

Applies only to repeated fields (not map, whose collection stays the configured map type). The element type is chosen by the usual scalar/string/bytes/message rules and substituted into the collection template. A rule that does not match a field of a generated message produces CodeGenWarning::FieldTypeRuleMatchedNothing.

§feature_overrides: Vec<(String, FeatureOverride)>

Path-scoped editions feature overrides, applied by mutating the parsed descriptors before generation.

Each entry pairs a fully-qualified proto path prefix with a FeatureOverride. Paths are matched with the same proto-segment-aware logic as bytes_fields: a rule may name a type (".my.pkg.E"), a field (".my.pkg.Msg.e"), a package/message prefix, or "." for everything the override targets. Leading dots are optional, trailing dots are ignored, and blank/all-dot entries match nothing. Map enum values match the outer map field path; oneof enum variants match the direct field path.

The mutated descriptors are what codegen — and, under reflection, the embedded descriptor pool — see, so runtime reflection and descriptor-driven dynamic JSON stay consistent with the generated types for both enum-scoped and field-scoped rules; see each variant’s docs for its semantics. A rule that matches nothing is reported as CodeGenWarning::FeatureOverrideMatchedNothing through generate_with_diagnostics (the plain generate entry point discards warnings). Overrides never change the wire format. The default is empty, so generated output and semantics are unchanged unless configured.

§unboxed_oneof_fields: Vec<String>

Fully-qualified proto paths whose message-typed oneof variants should not be wrapped in Box<T>. By default every message/group oneof variant is boxed (so recursive types compile); entries here opt matching variants out, storing the message inline in the enum.

Each entry is a proto path prefix matched with the same proto-segment-aware logic as bytes_fields ("." matches every variant). Recursive variants cannot be stored inline (the type would be unsized): an entry naming one exactly is rejected at codegen time, while a broader prefix entry silently keeps recursive variants boxed and inlines the rest.

§strict_utf8_mapping: bool

Honor features.utf8_validation = NONE by emitting Vec<u8> / &[u8] for such string fields instead of String / &str.

When false (the default), buffa emits String for all string fields and validates UTF-8 on decode — stricter than proto2 requires, but ergonomic and safe.

When true, string fields with utf8_validation = NONE (all proto2 strings by default, and editions fields that opt into NONE) become Vec<u8> / &[u8]. Decode skips validation; the caller decides at the call site whether to std::str::from_utf8 (checked) or from_utf8_unchecked (trusted-input fast path). This is the only sound Rust mapping when strings may actually contain non-UTF-8 bytes.

This is a breaking change for proto2 — enable only for new code or when profiling identifies UTF-8 validation as a bottleneck.

§allow_message_set: bool

Permit option message_set_wire_format = true on input messages.

MessageSet is a legacy Google-internal wire format that wraps each extension in a group structure instead of using regular field tags. When false (the default), encountering such a message is a codegen error — the flag exists to make MessageSet use explicit, since the format is obsolete outside of interop with very old Google protos.

§generate_text: bool

Whether to emit impl buffa::text::TextFormat on generated message structs for textproto (human-readable text format) encoding/decoding.

When this is true, the downstream crate must enable the buffa/text feature for the runtime encoder/decoder.

§emit_register_fn: bool

Whether the per-package .mod.rs stitcher emits __buffa::register_types(&mut TypeRegistry).

Default true. The fn aggregates Any type entries and extension entries for every message in the package. Set to false for crates that don’t use extensions/Any, or that hand-roll registration (e.g. buffa-types’ register_wkt_types, which knows the JSON-Any is_wkt special-casing the generic fn does not). The per-message __*_JSON_ANY / __*_TEXT_ANY consts are still emitted; only the aggregating fn is suppressed.

§file_per_package: bool

Emit one <dotted.package>.rs per proto package instead of the per-proto-file content set plus <pkg>.mod.rs stitcher.

The single file inlines what the stitcher would otherwise include!, producing the same __buffa::{view,oneof,ext,...} module structure. Intended for Buf Schema Registry generated SDKs, whose lib.rs synthesis builds the module tree from <dotted.package>.rs filenames.

Under strategy: directory this only sees one directory’s files per invocation, so the input module must be PACKAGE_DIRECTORY_MATCH-clean (one package per directory) for the output to be complete. BSR-hosted modules satisfy this by lint default. If a package spans multiple directories, separate invocations each emit their own <pkg>.rs and the last write wins — silent partial output, not a codegen error.

§type_attributes: Vec<(String, String)>

Custom attributes to inject on generated types (messages, enums, and oneof enums — the latter matched on the oneof’s own path, .my.pkg.MyMessage.my_oneof).

Each entry is (proto_path, attribute). The proto_path is matched as a prefix against the fully-qualified proto name: "." applies to all types, ".my.pkg" to types in that package, ".my.pkg.MyMessage" to a specific type. The attribute is one or more outer Rust attributes, each written with its #[...] (e.g., "#[derive(serde::Serialize)]"). generate returns CodeGenError::InvalidCustomAttribute for any other string, an empty one included. The same rule holds for the five attribute lists below.

When using a custom serde::Serialize derive, follow the requirements documented by buffa_build::Config::type_attribute: disable unknown-field preservation for generated messages and enable the json feature for buffa’s EnumValue and MessageField serde implementations. Do not combine a custom derive with generated JSON implementations.

§field_attributes: Vec<(String, String)>

Custom attributes to inject on generated struct fields.

Each entry is (proto_path, attribute). The proto_path is matched as a prefix against the fully-qualified field path (e.g., ".my.pkg.MyMessage.my_field"). "." applies to all fields. Oneof variants are matched as ".my.pkg.MyMessage.my_oneof.variant"; the struct field holding the oneof is not reached, see oneof_struct_field_attributes.

§message_attributes: Vec<(String, String)>

Custom attributes to inject on generated message structs only (not enums).

Same path-matching semantics as type_attributes, but only applied to message structs, not enum types. Useful for struct-only attributes like #[serde(default)].

§enum_attributes: Vec<(String, String)>

Custom attributes to inject on generated enum types only (not messages).

Same path-matching semantics as type_attributes, but only applied to enum types. Useful for enum-only attributes like #[derive(strum::EnumIter)] when the user does not want to apply the same attribute to every message in the matched scope.

§oneof_attributes: Vec<(String, String)>

Custom attributes to inject on generated oneof enums only (not messages, not regular enums).

Same path-matching semantics as type_attributes, matched against the oneof’s fully-qualified path (.pkg.Message.oneof_name). Useful when a oneof needs a different attribute set than the surrounding types — e.g. applying #[derive(serde::Serialize)] to oneofs while a separate enum_attributes entry puts a different serde derive on the regular enums. When the surrounding messages use the same custom derive, follow the buffa_build::Config::type_attribute requirements for unknown fields and the json feature.

§oneof_struct_field_attributes: Vec<(String, String)>

Custom attributes to inject on a message struct’s field holding a oneof (the Option<OneofEnum> member), not on the oneof’s variants or the oneof enum.

Same path-matching semantics as type_attributes, matched against the oneof’s fully-qualified path (.pkg.Message.oneof_name). field_attributes never reaches this field: on the oneof’s path it matches only the variants (.pkg.Message.oneof_name.variant).

Applies to the owned message struct only; the view structs do not get the attribute.

§gate_impls_on_crate_features: bool

Wrap generated impls in #[cfg(feature = "...")] instead of emitting them unconditionally.

When true, the impls controlled by generate_json, generate_views, and generate_text are emitted wrapped in #[cfg(feature = "json" | "views" | "text")] (or #[cfg_attr(feature = ..., ...)] for derives and field attributes) rather than unconditionally. The consuming crate must define matching Cargo features that enable the corresponding runtime support, e.g.:

[features]
json  = ["buffa/json", "dep:serde", "dep:serde_json"]
views = []
text  = ["buffa/text"]

The generate_* flags still control whether an impl kind is emitted at all — this flag only controls whether it is cfg-gated. generate_arbitrary is always cfg_attr-gated on feature = "arbitrary" regardless of this flag, because arbitrary is an optional dependency by design.

When generate_reflection is also on, the reflection impls are gated on feature = "reflect" alongside json/views/text. To gate only reflection without gating json/views/text, use gate_reflect_on_crate_feature instead.

This is the mechanism that lets buffa-descriptor and buffa-types ship every impl while keeping the codegen toolchain (buffa-codegen/buffa-build/protoc-gen-reallyme-buffa) lean: those crates depend on buffa-descriptor with default-features = false and so don’t pull serde/serde_json/base64. Most consumers don’t need this — they decide at build-script time whether to generate JSON, and if they say yes, they want impl Serialize to just exist.

§generate_with_setters: bool

Generate with_* builder-style setter methods for explicit-presence fields.

Each explicit-presence scalar, bytes, or enum field gets a pub fn with_<name>(mut self, value: T) -> Self method that wraps the value in Some and returns self, enabling chained construction:

ⓘ
let req = MyRequest::default()
    .with_name("alice")
    .with_timeout_ms(30_000);

Fields that receive a setter: proto3 optional, proto2 optional, and editions fields with field_presence = EXPLICIT.

Fields that do not receive a setter: message fields (MessageField<T>), repeated fields, map fields, oneof variant fields, proto2 required fields, and any implicit-presence field.

There is no clear_<name> companion — to clear a field, assign None directly: msg.name = None;.

Defaults to true.

§map_entries_omit_defaults: bool

Encode map entries as prost does: leave an entry’s key or value out when it holds what a missing field decodes to, and a message value when it encodes to nothing.

Off, every entry carries both fields, as the C++ and Java runtimes write them. Decoding reads either; a -0.0 float value is left out and so decodes as 0.0. prost leaves out a message value equal to its default, so a value that still encodes a field, such as one with a required field at its default, is written here and not by prost.

Applies to the owned, view and lazy view encoders of the messages generated in this run: types generated without it, the well-known types and DynamicMessage write both fields. With CodecStrategy::Table, messages with a map field keep the unrolled codec, and a codec_strategy_in rule that selects the table for such a message by its exact path is a CodeGenError. buffa_build::Config::map_entries_omit_defaults has the details.

Defaults to false.

§generate_reflection: bool

Generate impl Reflectable for owned message types (bridge mode).

When enabled, each generated message gets an impl ::buffa_descriptor::reflect::Reflectable whose reflect() round-trips through DynamicMessage (encode → decode → reflective handle), and the package’s __buffa::reflect submodule embeds the FileDescriptorSet bytes plus a lazily-built DescriptorPool.

Runtime requirements — the consuming crate must depend on:

  • buffa-descriptor with the reflect feature.
  • std (the lazy pool accessor uses std::sync::OnceLock).

When gate_impls_on_crate_features is on, the impls are wrapped in #[cfg(feature = "reflect")] so the consuming crate can opt out per build.

Performance — reflect() is one full encode/decode round-trip plus a heap allocation. The first call also pays a one-time pool build cost (linking the embedded FileDescriptorSet). For zero-copy reflective access over view types without the round-trip, additionally enable generate_reflection_vtable.

Binary size — by default each package embeds its own copy of the full FileDescriptorSet (transitive closure), so a multi-package run duplicates the FDS bytes per package. Enable shared_descriptor_pool to embed one shared copy at the module-tree root instead.

Defaults to false.

§generate_reflection_vtable: bool

Emit vtable-mode reflection: impl ReflectMessage / impl ReflectElement on the owned message structs and (when views are generated) the view types, and switch the owned Reflectable::reflect() body to borrow self (ReflectCow::Borrowed(self)) instead of the bridge round-trip.

Reflective access then reads struct fields in place — no encode/decode round-trip and no per-field allocation — for both a decoded view and an in-memory owned message.

Requires generate_reflection (the impls resolve against the same embedded DescriptorPool) but not generate_views — with views off, only the owned impls are emitted. Set via ReflectMode::VTable — front-ends expose it as buffa_build::Config::reflect_mode / protoc-gen-reallyme-buffa’s reflect_mode=vtable.

Defaults to false.

§shared_descriptor_pool: bool

Deduplicate the embedded reflection descriptor pool across packages.

With generate_reflection on, each package normally embeds its own copy of the full-closure FileDescriptorSet (FILE_DESCRIPTOR_SET_BYTES). For a multi-package run those copies are byte-identical, so the crate carries the same bytes once per package — which dominates generated-crate size for large proto trees.

When this is true, generate instead emits per-package __buffa::reflect modules that delegate to a single shared __buffa_fds module at the module-tree root. Every consumer path (pkg::descriptor_pool(), pkg::FILE_DESCRIPTOR_SET_BYTES, pkg::__buffa::reflect::*) keeps resolving; it just aliases the one shared copy, and all packages observe the same DescriptorPool instance.

The shared root module itself is emitted by the module-tree builder (buffa-build, or protoc-gen-reallyme-buffa-packaging with its matching shared_descriptor_pool=true), not by generate, so this mode requires one of those front-ends to assemble the tree — unless shared_descriptor_pool_root is set, in which case the root can live anywhere the caller assembled it. Consumers that wire the per-package modules by hand should leave both false/None (the default), which keeps the self-contained per-package embedding.

Use the same setting for every codegen run assembled into one module tree. Packages generated with this set to false keep their own pools even when sibling packages delegate to a shared pool; this mixed setup is not diagnosed.

Defaults to false. generate errors when this is on without generate_reflection.

§shared_descriptor_pool_root: Option<String>

When shared_descriptor_pool is on, use this path to the shared __buffa_fds module verbatim instead of computing a super::-relative one.

The default super:: path assumes one crate hosts the whole package tree as nested modules. A workspace with one crate per package has no such tree to climb; this field lets the caller point at wherever they assembled shared_descriptor_root_module’s output instead — a separate crate, a re-exported alias, anything.

The target is a contract, not a free-form value: it must be shared_descriptor_root_module’s output, pub and nameable from every package this and every other codegen run in the tree emits, gated the same way as reflect_feature_gate if that’s set, built against a semver-compatible buffa-descriptor, and — like the plugin path’s shared_descriptor_pool (see the guide’s “spans both plugins” note) — contain every message this generate() run reflects on. A root missing a type fails at runtime with a reflect() lookup panic, not at generate() or cargo build time.

Must be an absolute (::-prefixed) or crate-relative path of plain ::-separated identifiers — no generic or parenthesized arguments — since the same string is spliced verbatim at every package depth. generate rejects a malformed value immediately, before splicing it into generated source. Example: "::my_shared_fds_crate::__buffa_fds".

None (the default) keeps the super::-relative behavior.

§shared_corpus_context: Option<SharedCorpusContext>

Reuse a SharedCorpusContext built once by SharedCorpusContext::new instead of re-deriving the corpus-wide oneof/pointer-repr resolution and comment collection on every generate() call — the win for a one-crate-per-package workspace that generates each package from one whole-corpus FileDescriptorSet with only extern_paths varying per call. The context must have been built from the same files and the same unboxed_oneof_fields/pointer_fields as the call using it; generate checks and returns CodeGenError::SharedCorpusContextMismatch otherwise.

None (the default) recomputes on every call.

§gate_reflect_on_crate_feature: bool

Gate the reflection impls behind a reflect crate feature, without gating json/views/text (unlike gate_impls_on_crate_features, which gates them all together).

Used by crates that ship view/text impls unconditionally but want the reflection surface — which pulls a buffa-descriptor dependency and std — to be opt-in. buffa-types is the motivating case: its WKT views are always available, but impl ReflectMessage for them is gated behind buffa-types’s reflect feature.

When gate_impls_on_crate_features is already on, reflection is gated regardless and this flag is ignored.

A low-level knob for crates whose generated code is a public interface (buffa-types, the conformance harness). Set directly by gen_wkt_types and exposed through buffa_build::Config::gate_reflect_on_crate_feature (currently #[doc(hidden)]).

Defaults to false.

§idiomatic_enum_aliases: bool

Emit idiomatic UpperCamelCase constant aliases alongside each enum variant.

Protobuf style names enum values in SHOUTY_SNAKE_CASE, conventionally prefixed with the enum name (RULE_LEVEL_HIGH). Those names remain the definitive Rust variants — they are guaranteed unique and valid by protobuf, and existing references (including Debug output) are unchanged. When this is enabled, codegen additionally emits associated consts with the prefix stripped and the name converted to UpperCamelCase (RULE_LEVEL_HIGH → High), so downstream code can write RuleLevel::High.

The conversion is lossy, so two values can collide (FOO_BAR and FOO__BAR both map to FooBar). The rule is all-or-nothing per enum: if any two values would collide after conversion, or a value would yield an invalid identifier, no aliases are emitted for that enum (a CodeGenWarning and an enum doc note explain why). This keeps every match either fully SHOUTY_SNAKE_CASE or fully idiomatic, never a forced mix.

The aliases are associated consts, which work in pattern position too: a match written entirely against aliases is still exhaustiveness-checked (the “non-exhaustive” error names the underlying SHOUTY_SNAKE_CASE variant, since that is the canonical name).

Defaults to true: the aliases are purely additive (the proto names remain the variants, and Debug is unchanged), so enabling by default is backward-compatible, and the all-or-nothing rule guarantees correctness on any enum.

§idiomatic_imports: bool

Emit use-backed short type names at the package root instead of fully-qualified paths, so generated code reads like hand-written Rust (pub at: MessageField<Timestamp> instead of pub at: ::buffa::MessageField<::buffa_types::google::protobuf::Timestamp>).

Requires file_per_package: only there is the package-root scope a single-writer file whose complete name set is known at generation time. In the multi-file layout the stitcher include!-merges every proto’s content files into the shared root scope, where emitted use directives could collide across files — generate returns an error for that combination rather than silently ignoring the flag.

Off by default; default output is byte-for-byte unchanged. Short names are always backed by an explicit use (never glob reliance), are refused when they would collide with the package’s own items or names referenced bare by sibling emissions, and fall back to parent-module qualification and then the fully-qualified path. The short-name assignment (use block and per-path choices) is computed from a collection pre-pass and is stable under .proto file reordering; item order within the file still follows input order, so whole-file output is not reorder-invariant. The pre-pass generates the package twice, roughly doubling codegen time for it.

Scope: only package-root type declarations (struct fields, oneof Option wrappers) are shortened. Impl bodies, nested-message modules, and __buffa internals keep fully-qualified paths — the readability payoff lands where consumers look (struct definitions and rustdoc), not in the codec internals.

Experimental means: the generated-output shape may change between releases (requiring regeneration of checked-in code), and the option itself may be renamed or removed outside semver guarantees.

§idiomatic_field_names: bool

Convert proto field and oneof names to idiomatic snake_case Rust identifiers (webMessageInfo → web_message_info), matching prost-build’s behavior for protos that use camelCase field names.

Only the generated Rust source names change — struct fields, view accessors, has_*/with_* methods. Every name-keyed protocol surface keeps the descriptor’s names: the wire format keys on field numbers, JSON uses json_name (with the original proto name still accepted on parse, per the proto3 JSON spec), text format and reflection lookups use the original proto name. Enum values and message/module names are not affected (see idiomatic_enum_aliases for enums), and extension accessors are SHOUTY_SNAKE_CASE constants derived independently of this option.

Word boundaries match heck’s (and therefore prost-build’s) segmentation, including acronym handling (XMLHttpRequest → xml_http_request) and digit-transparent case boundaries (v2Field → v2_field). The one deliberate divergence from prost: the conversion is insertion-only and never deletes underscores the proto author wrote, so it is the identity on every name that is already a valid snake_case identifier (_foo stays _foo, where prost emits foo).

The conversion is lossy, so two members of one message can collide (userName and user_name). Unlike enum aliases — which are additive consts and can simply be suppressed — a field rename replaces the canonical name, so collisions are resolved deterministically instead: a member whose name is already snake_case keeps it, a converted field that collides gets an _f<field_number> suffix (userName = 12 → user_name_f12), and a converted oneof that collides keeps its verbatim proto name. If an adjusted field name still collides, the changed members in that collision group fall back to their verbatim proto names. Each adjustment is reported as a CodeGenWarning::IdiomaticFieldNamesAdjusted. protoc rejects the underlying name collisions for proto3 and editions files (conflicting json_names), so adjustments are only reachable from proto2 inputs.

Defaults to false: a rename is not backward-compatible for existing consumers of generated camelCase fields, and verbatim emission keeps the .proto file the source of truth. Opt in for prost parity.

§feature_gate_names: FeatureGateNames

Crate feature names used by the #[cfg(feature = "...")] gates that gate_impls_on_crate_features and gate_reflect_on_crate_feature emit.

Defaults to "json" / "views" / "text" / "reflect". Override a name when the consuming crate gates the same concern behind a different feature name (e.g. its JSON support behind a serde feature). Inert unless one of the gating flags is on.

§type_name_prefix: String

Prefix prepended to every locally-generated Rust type name.

With prefix "Rpc", message User {} generates struct RpcUser, its view becomes RpcUserView / RpcUserOwnedView, and every cross-reference (fields, oneof variants, maps, extensions) uses the prefixed name. Useful in multi-protocol systems where generated types from different domains would otherwise collide with each other or with a canonical hand-written model.

The prefix applies to message structs and enum types (top-level and nested, plus their derived view/owned-view types). It does not apply to:

  • module names (message Outer still nests under pub mod outer). A prefix can remove a module’s trailing _: the nested types of message item are in item_ beside struct item, and in item beside struct Pbitem,
  • oneof enums (structurally namespaced under __buffa::oneof::, named after the oneof declaration, not the message),
  • types mapped away via extern_paths or the automatic well-known-type mapping (their names are owned by the external crate),
  • wire-format and JSON output (proto names, TYPE_URLs, and JSON field names are unaffected — this is a pure Rust-identifier rename).

When another codegen run references these prefixed types via its own extern_paths mapping, the mapped Rust path must spell out the prefixed name (e.g. ::crate_a::RpcUser) — the proto name carries no prefix, so the mapping is not derived automatically. Prefix-induced name collisions (e.g. message RpcUser alongside message User with prefix Rpc) are not detected here; they surface as ordinary duplicate-definition errors when the generated code is compiled.

Must be PascalCase ([A-Z][A-Za-z0-9]*) — an ASCII uppercase letter followed by ASCII letters and digits — so the prefixed names stay conventionally cased; generation fails with CodeGenError::InvalidTypeNamePrefix otherwise. Defaults to "" (no prefix).

§exclude_packages: Vec<String>

Proto packages to exclude from code generation (default: empty).

Each entry is a normalized proto package name without a leading dot (e.g. "buf.validate", "gnostic.openapi.v3"). A package matches if it equals an entry exactly or starts with "<entry>." — so "buf.validate" excludes both buf.validate and buf.validate.priv.

Use this when .proto files from option-only packages (e.g. buf/validate/validate.proto, gnostic annotations) end up in the generate set via include_imports or directory globbing, but you do not want Rust types for those packages. Their descriptors remain in the compilation for type resolution; only code generation is skipped.

If you exclude a package that other kept files reference as a field type, you must also add an extern_path mapping for it, or the generated code will contain dangling super::…::Type paths that fail to compile (CodeGenWarning::ExcludedPackageFieldRef names the offending field first).

Entries are proto package names with no empty segments (e.g. "buf.validate", "gnostic.openapi.v3"); a leading dot is accepted and stripped at generation time. generate_with_diagnostics rejects anything else, and warns with CodeGenWarning::ExcludePackageMatchedNothing for an entry that matches no package in the input.

§codec_strategy: CodecStrategy

The CodecStrategy of every message that no codec_strategy_in rule covers (default: CodecStrategy::Unrolled).

Under CodecStrategy::Table a message that cannot use the table stays unrolled, and codegen reports one CodeGenWarning::TableCodecFallbackSummary for the run.

§codec_strategy_in: Vec<(String, CodecStrategy)>

Path-scoped overrides for codec_strategy. Each entry is (proto_path_prefix, strategy), with a leading dot (".pkg.Msg").

Matching uses the same proto-segment-aware prefix rules as preserve_unknown_fields_in: a rule covers the message it names and every message nested inside it, "." covers everything, and the last matching rule wins.

A CodecStrategy::Table rule that covers a message that cannot use the table keeps it unrolled and counts it in the CodeGenWarning::TableCodecFallbackSummary. If the rule names the message by its exact path, that is an error instead, because the rule asked for something impossible. A rule that matches no generated message produces a CodeGenWarning::CodecStrategyRuleMatchedNothing.

A rule does not extend to the messages a message holds; see CodecStrategy::Table.

Implementations§

Source§

impl CodeGenConfig

Source

pub fn reflect_feature_gate(&self) -> Option<&str>

The crate feature the reflection surface is gated behind, or None when reflection is unconditional.

Front-ends emitting the shared descriptor root module (see shared_descriptor_root_module and shared_descriptor_pool) must gate it with this exact value, so the root module and the per-package delegations that reference it appear and disappear together.

Trait Implementations§

Source§

impl Clone for CodeGenConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CodeGenConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for CodeGenConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.