Skip to main content

buffa_codegen/
context.rs

1// Modified by ReallyMe Technologies Limited.
2//! Code generation context and descriptor-to-Rust mapping state.
3
4use std::borrow::Cow;
5use std::collections::{HashMap, HashSet};
6use std::sync::Arc;
7
8use crate::features::{self, ResolvedFeatures};
9use crate::generated::descriptor::field_descriptor_proto::Type;
10use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
11use crate::oneof::to_snake_case;
12use crate::CodeGenConfig;
13
14/// The single reserved module name under which all ancillary generated types
15/// (views, oneof enums, extensions, `register_types`) live.
16///
17/// See `DESIGN.md` → "Generated code layout" for the full layout. The name
18/// is checked against proto package segments and message-module names by
19/// `validate_file`; a collision is a hard error.
20pub const SENTINEL_MOD: &str = "__buffa";
21
22/// A Rust type path split at the target-package boundary.
23///
24/// Returned by [`CodeGenContext::rust_type_relative_split`]. The full owned
25/// path is `to_package + within_package` (concatenated with `::`); ancillary
26/// kinds insert their `__buffa::<kind>::` prefix between the two halves.
27#[derive(Debug, Clone)]
28pub struct SplitPath {
29    /// Path from the current emission scope to the **target package root**.
30    ///
31    /// One of:
32    /// - empty (same package, nesting 0)
33    /// - `"super::super"` (same package, nesting > 0)
34    /// - `"super::…::other_pkg"` (cross-package local)
35    /// - `"::extern_crate::pkg"` (extern type — absolute, nesting-independent)
36    pub to_package: String,
37    /// Path from the target package root to the type itself
38    /// (e.g. `"Foo"` or `"outer::Inner"`).
39    pub within_package: String,
40    /// `true` when `to_package` is an absolute (`::`/`crate::`) extern path.
41    /// Extern paths don't depend on the caller's nesting depth.
42    pub is_extern: bool,
43}
44
45/// Shared context for a code generation run.
46///
47/// Holds the full set of file descriptors and a mapping from fully-qualified
48/// protobuf type names to their Rust type paths. This is needed because a
49/// field in one `.proto` file may reference a message defined in another.
50pub struct CodeGenContext<'a> {
51    /// All file descriptors (both requested and dependencies).
52    pub files: &'a [FileDescriptorProto],
53    /// Code generation configuration.
54    pub config: &'a CodeGenConfig,
55    denied_view_json: std::cell::OnceCell<HashSet<String>>,
56    guarded_reflection_messages: std::cell::OnceCell<HashSet<String>>,
57    /// Map from fully-qualified protobuf name (e.g., ".my.package.MyMessage")
58    /// to Rust type path (e.g., "my::package::MyMessage").
59    ///
60    /// Nested types use module-qualified paths:
61    /// ".pkg.Outer.Inner" → "pkg::outer::Inner" (not "pkg::OuterInner").
62    pub type_map: HashMap<String, String>,
63    /// Map from fully-qualified protobuf name to its proto package.
64    ///
65    /// Used by `rust_type_relative` to compute `super::`-based relative
66    /// paths for cross-package references within the same compilation.
67    package_of: HashMap<String, String>,
68    /// Map from fully-qualified enum name to its resolved `enum_type` feature.
69    ///
70    /// The `enum_type` feature determines whether an enum is OPEN or CLOSED.
71    /// It's resolved from the ENUM's own file → message → enum feature chain,
72    /// NOT from the referencing field's chain. protoc does not propagate
73    /// enum-level `enum_type` into field options (verified 2026-03), so
74    /// callers must look this up via `is_enum_closed`.
75    enum_closedness: HashMap<String, bool>,
76    /// Map from fully-qualified enum name to its first declared value's
77    /// number — the enum type's implicit default per spec. Non-zero only for
78    /// closed (proto2 / editions-closed) enums; used to decide whether a bare
79    /// enum field opened by an enum-type override needs an explicit generated
80    /// default (`EnumValue::Known(first)` instead of the derived wire-zero).
81    enum_first_value: HashMap<String, i32>,
82    /// Enum FQN → proto names of its values whose generated item is
83    /// `#[deprecated]`; see [`Self::enum_value_is_deprecated`].
84    /// Built on first use, and consulted only when a field declares an explicit
85    /// enum `default_value`, so the common path never walks the descriptor set.
86    deprecated_enum_values: std::cell::OnceCell<HashMap<String, HashSet<String>>>,
87    /// Map from fully-qualified protobuf element name to its source comment.
88    ///
89    /// Keys use dotted FQN form without a leading dot, matching the `proto_fqn`
90    /// values already threaded through codegen: `"pkg.Message"`,
91    /// `"pkg.Message.field_name"`, `"pkg.Enum.VALUE_NAME"`,
92    /// `"pkg.Message.oneof_name"`.
93    ///
94    /// Built by walking each file's descriptor tree alongside its
95    /// `SourceCodeInfo` (which uses index-based paths). This up-front
96    /// translation means codegen call sites can look up comments by the
97    /// proto FQN they already have, rather than threading index-based paths
98    /// through every function signature.
99    comment_map: Arc<HashMap<String, String>>,
100    /// Nested-types module name of each message whose module is not named
101    /// `snake_case(Name)`, keyed by the leading-dot FQN (`".pkg.Msg"`).
102    ///
103    /// [`deconflict_modules`] chooses the names. The ancillary trees under
104    /// `__buffa` use the same name as the owned tree.
105    nested_module_names: HashMap<String, String>,
106    /// Variant paths (leading-dot form) resolved from
107    /// `config.unboxed_oneof_fields` whose oneof variants are stored inline.
108    /// Built once by [`resolve_unboxed_variants`](crate::oneof::resolve_unboxed_variants);
109    /// never contains recursive variants. See [`oneof_unboxed`](Self::oneof_unboxed).
110    unboxed_oneof_variants: Arc<HashSet<String>>,
111    /// Singular message-field paths (leading-dot form) whose resolved
112    /// [`PointerRepr`](crate::PointerRepr) is `Inline`. Built once by
113    /// [`resolve_inlined_fields`](crate::oneof::resolve_inlined_fields); never
114    /// contains recursive fields. [`pointer_repr`](Self::pointer_repr) demotes
115    /// any raw `Inline` not in this set to `Box`.
116    inlined_message_fields: Arc<HashSet<String>>,
117    /// Non-fatal diagnostics accumulated during generation (e.g. an enum whose
118    /// idiomatic CamelCase aliases were suppressed by a naming conflict).
119    ///
120    /// Interior-mutable so deeply-nested codegen helpers can record a warning
121    /// through the shared `&CodeGenContext` without threading a sink through
122    /// every signature. Drained by [`generate_with_diagnostics`] after
123    /// generation; callers surface them as build warnings. The `RefCell` commits
124    /// the context to single-threaded use; switch to a `Mutex` if package
125    /// generation is ever parallelized.
126    ///
127    /// [`generate_with_diagnostics`]: crate::generate_with_diagnostics
128    warnings: std::cell::RefCell<Vec<crate::CodeGenWarning>>,
129    /// The messages generated with the table codec, planned by
130    /// [`plan_table_codec`](Self::plan_table_codec). Unset, which is the same
131    /// as empty, unless a table codec was requested.
132    table_plan: std::cell::OnceCell<crate::table_plan::TablePlan>,
133    /// Field-rename exceptions for `CodeGenConfig::idiomatic_field_names`:
134    /// `(proto_name, field_number)` → final Rust source name, present only
135    /// for fields whose context-free snake_case conversion was adjusted by a
136    /// collision (see [`crate::field_names`]). Empty when the option is off
137    /// or no collisions exist — the common case.
138    field_renames: HashMap<(String, i32), String>,
139    /// Oneof proto names that keep their verbatim spelling under
140    /// `idiomatic_field_names` (their snake_case conversion collided).
141    oneof_keep_verbatim: HashSet<String>,
142    /// `(proto_name, field_number)` → Rust source name, for a field whose
143    /// keyword-escaped identifier is also another member's name in at least
144    /// one message that declares the field (see [`crate::field_names`]).
145    keyword_field_renames: HashMap<(String, i32), String>,
146    /// Proto oneof name → Rust source name; the oneof counterpart of
147    /// `keyword_field_renames`.
148    keyword_oneof_renames: HashMap<String, String>,
149    /// Package-root import phase for `CodeGenConfig::idiomatic_imports`
150    /// (file_per_package mode only). [`ImportsPhase::Off`] outside the
151    /// two-pass window, so every path resolver below is a no-op by default.
152    ///
153    /// Interior-mutable for the same reason as `warnings`: the leaf path
154    /// resolvers ([`rust_type_relative`](Self::rust_type_relative),
155    /// [`root_runtime_path`](Self::root_runtime_path)) participate through
156    /// the shared `&CodeGenContext` without threading a registry through
157    /// every emission signature.
158    ///
159    /// [`ImportsPhase::Off`]: crate::imports::ImportsPhase::Off
160    imports: std::cell::RefCell<crate::imports::ImportsPhase>,
161}
162
163/// The immediate child-package segment names directly under `package`.
164///
165/// For `package` `"foo"` and known packages `{foo, foo.oof, foo.bar.baz}`, this
166/// is `{"oof", "bar"}` — the first segment after the `"foo."` prefix of each
167/// deeper package. These are exactly the sub-package module names that will be
168/// siblings of `foo`'s message-nesting modules.
169fn child_package_segments(package: &str, all_packages: &HashSet<String>) -> HashSet<String> {
170    let prefix = if package.is_empty() {
171        String::new()
172    } else {
173        format!("{package}.")
174    };
175    all_packages
176        .iter()
177        .filter_map(|p| {
178            let rest = if package.is_empty() {
179                Some(p.as_str())
180            } else {
181                p.strip_prefix(&prefix)
182            };
183            rest.filter(|r| !r.is_empty())
184                .map(|r| r.split('.').next().unwrap_or(r).to_string())
185        })
186        .collect()
187}
188
189/// Module names that cannot hold a message's nested types in any scope.
190///
191/// `self`, `super` and `crate` cannot name a module. The output of
192/// `derive(Arbitrary)` starts its paths with `arbitrary::`, and beside a
193/// module named `arbitrary` those paths resolve to the module. The name is
194/// reserved whether or not
195/// [`generate_arbitrary`](crate::CodeGenConfig::generate_arbitrary) is on, so
196/// that a crate and a crate that refers to its types through `extern_path`
197/// choose the same module.
198const RESERVED_MODULE_NAMES: [&str; 4] = ["self", "super", "crate", "arbitrary"];
199
200/// A module name that is taken at package level, in addition to
201/// [`RESERVED_MODULE_NAMES`]: `__buffa::view::oneof` is the root of the
202/// view-oneof tree, beside the view modules of the package's messages.
203const PACKAGE_RESERVED_MODULE_NAME: &str = "oneof";
204
205/// The nested-types module of a message that an exact `extern_path` entry
206/// maps to `rust_path`: the name a buffa-generated crate gives the module
207/// beside a type of that name. `package_level` is true for a message declared
208/// in a package and false for a nested one. A sub-package or a second type of
209/// the module's name in that crate does not show in the entry, and is not
210/// accounted for.
211fn extern_override_module(name: &str, rust_path: &str, package_level: bool) -> String {
212    let type_name = last_path_segment(rust_path);
213    let mut module = to_snake_case(name);
214    if RESERVED_MODULE_NAMES.contains(&module.as_str())
215        || (package_level && module == PACKAGE_RESERVED_MODULE_NAME)
216        || module == type_name
217    {
218        module.push('_');
219        while module == type_name {
220            module.push('_');
221        }
222    }
223    module
224}
225
226/// The last segment of a Rust path: the name a type declares in its module.
227fn last_path_segment(rust_path: &str) -> &str {
228    rust_path.rsplit("::").next().unwrap_or(rust_path)
229}
230
231/// Choose the nested-types module names for the messages of one scope: a
232/// package's top-level messages, or the messages nested in one message.
233///
234/// `message_names` are the messages' proto names in declaration order.
235/// `occupied` are the names a module cannot take in that scope, in addition to
236/// [`RESERVED_MODULE_NAMES`]: sub-package segments (issue #135), the Rust
237/// names of the scope's types, and at package level
238/// [`PACKAGE_RESERVED_MODULE_NAME`]. Returns one module name per input
239/// message, in the same order.
240///
241/// Each name is `snake_case(Name)` unless that is reserved or in `occupied`,
242/// in which case `_` is appended until the candidate is unique against:
243/// `occupied`, every message's raw module name, the `__buffa` sentinel, **and
244/// every already-assigned deconflicted name**. That last set, kept in
245/// `taken`, is what keeps two messages that would otherwise race to the same
246/// slot distinct (e.g. `Oof` and `Oof_` alongside sub-packages `oof` and
247/// `oof_` resolve to `oof__` and `oof___`, never both to `oof__`).
248///
249/// Colliding messages are assigned in a stable order (sorted by base name,
250/// then by proto name), so the per-message result is independent of
251/// declaration order: reordering the input files or messages never changes
252/// which name a given message receives.
253fn deconflict_modules(message_names: &[String], occupied: &HashSet<String>) -> Vec<String> {
254    let bases: Vec<String> = message_names.iter().map(|n| to_snake_case(n)).collect();
255    let is_occupied =
256        |base: &String| RESERVED_MODULE_NAMES.contains(&base.as_str()) || occupied.contains(base);
257    if !bases.iter().any(is_occupied) {
258        return bases;
259    }
260    // Seed with everything fixed: the occupied names, the sentinel, and every
261    // message's raw module name. Assigned deconflicted names are added as we go.
262    let mut taken: HashSet<String> = occupied.clone();
263    taken.insert(SENTINEL_MOD.to_string());
264    taken.extend(bases.iter().cloned());
265
266    // Result starts as the raw bases (correct for every non-colliding message),
267    // and colliding messages overwrite their slot. Assign in a stable order so
268    // the per-message suffix is independent of declaration order; two
269    // colliding messages can't both grab the same slot.
270    let mut out = bases.clone();
271    let mut order: Vec<usize> = (0..bases.len()).collect();
272    order.sort_by(|&a, &b| (&bases[a], &message_names[a]).cmp(&(&bases[b], &message_names[b])));
273    for i in order {
274        if !is_occupied(&bases[i]) {
275            continue;
276        }
277        let mut candidate = format!("{}_", bases[i]);
278        while taken.contains(&candidate) {
279            candidate.push('_');
280        }
281        taken.insert(candidate.clone());
282        out[i] = candidate;
283    }
284    out
285}
286
287/// The rustdoc note for a `kind` ("field" or "oneof") that the keyword-escape
288/// plan renamed to `resolved` (`self__`).
289fn keyword_rename_note(kind: &str, resolved: &str) -> String {
290    let stem = resolved.trim_end_matches('_');
291    format!(
292        " Note: `{stem}_`, the usual Rust name of this {kind}, is the name of another \
293         member of this message or of a message that declares the same {kind}, so this \
294         {kind} is `{resolved}`."
295    )
296}
297
298/// Parses a custom attribute string as one or more outer attributes.
299///
300/// The whole string must be `#[...]` attributes (`syn::Attribute::parse_outer`);
301/// a `///` doc comment is one. A string with any other token is an error: a
302/// bare `serde(skip)`, an inner attribute `#![...]`, or an attribute followed
303/// by an item or a field. So is a string with no attribute in it.
304fn parse_outer_attribute_string(attr_str: &str) -> syn::Result<proc_macro2::TokenStream> {
305    use syn::parse::Parser as _;
306
307    let parser = |input: syn::parse::ParseStream<'_>| {
308        // `//!` lexes as `#![doc = "..."]`, so this covers it too.
309        if input.peek(syn::Token![#]) && input.peek2(syn::Token![!]) {
310            return Err(input.error("an inner attribute `#![...]` is not accepted; write `#[...]`"));
311        }
312        let attrs = input.call(syn::Attribute::parse_outer)?;
313        if !input.is_empty() {
314            return Err(input.error("expected an outer attribute of the form `#[...]`"));
315        }
316        if attrs.is_empty() {
317            return Err(syn::Error::new(
318                proc_macro2::Span::call_site(),
319                "expected at least one `#[...]` attribute",
320            ));
321        }
322        Ok(quote::quote!(#(#attrs)*))
323    };
324    parser.parse_str(attr_str)
325}
326
327/// Parses the custom attribute string of the rule `(path, attr_str)`,
328/// reporting a string that is not one or more outer attributes as
329/// `CodeGenError::InvalidCustomAttribute`.
330fn parse_custom_attribute(
331    path: &str,
332    attr_str: &str,
333) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
334    parse_outer_attribute_string(attr_str).map_err(|err| {
335        crate::CodeGenError::InvalidCustomAttribute {
336            path: path.to_string(),
337            attribute: attr_str.to_string(),
338            detail: err.to_string(),
339        }
340    })
341}
342
343/// Checks every custom attribute rule of `config`, in the order of its six
344/// attribute lists, whether or not the rule's path matches a generated item.
345pub(crate) fn validate_custom_attributes(
346    config: &crate::CodeGenConfig,
347) -> Result<(), crate::CodeGenError> {
348    [
349        &config.type_attributes,
350        &config.field_attributes,
351        &config.message_attributes,
352        &config.enum_attributes,
353        &config.oneof_attributes,
354        &config.oneof_struct_field_attributes,
355    ]
356    .into_iter()
357    .flatten()
358    .try_for_each(|(path, attr_str)| parse_custom_attribute(path, attr_str).map(drop))
359}
360
361impl<'a> CodeGenContext<'a> {
362    /// Build a context from file descriptors, populating the type map.
363    ///
364    /// `effective_extern_paths` includes both user-provided mappings and any
365    /// auto-injected defaults (e.g., the WKT mapping). These are computed by
366    /// `crate::effective_extern_paths` before calling this constructor.
367    ///
368    /// File-level extern resolution (currently only `descriptor.proto` /
369    /// `compiler/plugin.proto` → `buffa-descriptor`) is **not** applied by
370    /// this constructor — use [`for_generate`](Self::for_generate), which
371    /// computes and passes the file-level mappings, when generating code
372    /// that may reference descriptor types.
373    ///
374    /// This constructor plans keyword-escaped member names over every file
375    /// in `files`. `for_generate` plans them over the generated files only.
376    pub fn new(
377        files: &'a [FileDescriptorProto],
378        config: &'a CodeGenConfig,
379        effective_extern_paths: &[(String, String)],
380    ) -> Self {
381        Self::with_extern_resolution(files, config, effective_extern_paths, &[], None)
382    }
383
384    /// Build a context with both package-level and file-level extern
385    /// mappings.
386    ///
387    /// `file_extern_paths` maps a `.proto` file's full path (as reported in
388    /// `FileDescriptorProto.name`, e.g. `"google/protobuf/descriptor.proto"`)
389    /// to a Rust module root. It takes priority over a package-level
390    /// `effective_extern_paths` match, which lets two files in the same proto
391    /// package (`google.protobuf`) resolve to different external crates —
392    /// `descriptor.proto` types to `buffa-descriptor`, every other
393    /// `google.protobuf` WKT to `buffa-types`. Without this split a single
394    /// package-keyed mapping would route everything to one crate or the
395    /// other.
396    ///
397    /// Per-type resolution priority (issue #111), most specific first: an
398    /// **exact** `extern_path` entry for a type's FQN, then the **file-level**
399    /// mapping above, then a **package/prefix** `extern_path` match, then the
400    /// **local** package path. See [`resolve_type_path`].
401    ///
402    /// File-level mappings are an internal mechanism used for the
403    /// auto-injected descriptor-types routing. They are not part of the
404    /// public `CodeGenConfig` API; user-facing `extern_path` entries are keyed
405    /// by proto package *or* type FQN.
406    ///
407    /// `generated_files` names the files that this run generates. Only their
408    /// messages take part in the keyword-escape plan
409    /// ([`crate::field_names::plan_keyword_escapes`]); `None` means every
410    /// file.
411    pub(crate) fn with_extern_resolution(
412        files: &'a [FileDescriptorProto],
413        config: &'a CodeGenConfig,
414        effective_extern_paths: &[(String, String)],
415        file_extern_paths: &[(String, String)],
416        generated_files: Option<&HashSet<String>>,
417    ) -> Self {
418        let mut type_map = HashMap::new();
419        let mut package_of = HashMap::new();
420        let mut enum_closedness = HashMap::new();
421        let mut nested_module_names = HashMap::new();
422
423        // Reuse the corpus-wide state a caller precomputed with
424        // `SharedCorpusContext::new`: it is identical for the same `files`
425        // and oneof/pointer-repr rules regardless of `effective_extern_paths`
426        // (the one thing that legitimately varies per call in a
427        // one-crate-per-package workspace), so this is an `Arc` clone
428        // instead of a fresh corpus-wide walk. `generate` has already
429        // checked that the context matches this call; this entry point is
430        // infallible, so it only asserts in debug builds.
431        let shared = match &config.shared_corpus_context {
432            Some(shared) => {
433                debug_assert!(
434                    shared.check(files, config).is_ok(),
435                    "shared_corpus_context does not match this call's files or rules"
436                );
437                shared.clone()
438            }
439            None => crate::SharedCorpusContext::new(files, config),
440        };
441        let unboxed_oneof_variants = Arc::clone(shared.unboxed_oneof_variants());
442        let inlined_message_fields = Arc::clone(shared.inlined_message_fields());
443        let comment_map = Arc::clone(shared.comment_map());
444
445        // Pre-pass: collect every package, and the top-level message names and
446        // Rust type names of each, in the descriptor set. Extern packages are
447        // included: without them a consumer emits `money::Currency` where the
448        // owning crate emits `money_::Currency`.
449        let mut all_packages: HashSet<String> = HashSet::new();
450        let mut pkg_message_names: HashMap<String, Vec<String>> = HashMap::new();
451        let mut pkg_type_names: HashMap<String, HashSet<String>> = HashMap::new();
452        for file in files {
453            let package = file.package.as_deref().unwrap_or("");
454            all_packages.insert(package.to_string());
455            let file_root = file
456                .name
457                .as_deref()
458                .and_then(|n| resolve_file_extern(n, file_extern_paths));
459            let local_module = package.replace('.', "::");
460            let messages = file.message_type.iter().map(|m| (m.name.as_ref(), true));
461            let enums = file.enum_type.iter().map(|e| (e.name.as_ref(), false));
462            for (name, is_message) in messages.chain(enums) {
463                let Some(name) = name else { continue };
464                // A per-type `extern_path` override (issue #111) makes the
465                // type extern: it emits no local item, so it must not
466                // reserve a name in this scope's deconfliction (#135).
467                let fqn = if package.is_empty() {
468                    format!(".{name}")
469                } else {
470                    format!(".{package}.{name}")
471                };
472                if effective_extern_paths
473                    .iter()
474                    .any(|(proto, _)| proto == &fqn)
475                {
476                    continue;
477                }
478                let (rust_path, _) = resolve_type_path(
479                    &fqn,
480                    name,
481                    file_root,
482                    &local_module,
483                    effective_extern_paths,
484                    &config.type_name_prefix,
485                );
486                pkg_type_names
487                    .entry(package.to_string())
488                    .or_default()
489                    .insert(last_path_segment(&rust_path).to_string());
490                if is_message {
491                    pkg_message_names
492                        .entry(package.to_string())
493                        .or_default()
494                        .push(name.clone());
495                }
496            }
497        }
498
499        // Resolve the deconflicted nested-types module name for every top-level
500        // message, batched per package so racing deconflictions stay distinct.
501        // Each package is an independent scope, so the populated map is the same
502        // regardless of `pkg_message_names` iteration order.
503        for (package, names) in &pkg_message_names {
504            let mut occupied = child_package_segments(package, &all_packages);
505            // A sub-package named `self`, `super` or `crate` is the module
506            // `crate_` (`escape_mod_ident`).
507            let escaped: Vec<String> = ["self", "super", "crate"]
508                .iter()
509                .filter(|name| occupied.contains(**name))
510                .map(|name| format!("{name}_"))
511                .collect();
512            occupied.extend(escaped);
513            occupied.insert(PACKAGE_RESERVED_MODULE_NAME.to_string());
514            if let Some(type_names) = pkg_type_names.get(package) {
515                occupied.extend(type_names.iter().cloned());
516            }
517            let modules = deconflict_modules(names, &occupied);
518            for (name, module) in names.iter().zip(modules) {
519                if module == to_snake_case(name) {
520                    continue;
521                }
522                let fqn = if package.is_empty() {
523                    format!(".{name}")
524                } else {
525                    format!(".{package}.{name}")
526                };
527                nested_module_names.insert(fqn, module);
528            }
529        }
530
531        for file in files {
532            let package = file.package.as_deref().unwrap_or("");
533            let file_features = features::for_file(file);
534            let proto_prefix = if package.is_empty() {
535                String::from(".")
536            } else {
537                format!(".{}.", package)
538            };
539
540            // The file-level extern root (the internal descriptor.proto →
541            // buffa-descriptor split) and the local package module. Per-type
542            // resolution (issue #111) layers exact/longest-prefix `extern_path`
543            // matching on top, via `resolve_type_path`, which preserves the
544            // historic priority: per-type exact → file-level → package prefix →
545            // local. The file-level check still outranks a package prefix so two
546            // files in the same proto package can route to different crates
547            // (descriptor.proto → buffa-descriptor, timestamp.proto →
548            // buffa-types).
549            let file_root = file
550                .name
551                .as_deref()
552                .and_then(|n| resolve_file_extern(n, file_extern_paths));
553            let local_module = package.replace('.', "::");
554
555            // Register top-level messages
556            for msg in &file.message_type {
557                if let Some(name) = &msg.name {
558                    let fqn = format!("{}{}", proto_prefix, name);
559                    let (rust_path, is_extern) = resolve_type_path(
560                        &fqn,
561                        name,
562                        file_root,
563                        &local_module,
564                        effective_extern_paths,
565                        &config.type_name_prefix,
566                    );
567
568                    // The module the message's nested types are in: the
569                    // resolved path's parent plus the module name. The name
570                    // was chosen above, except for a message with an exact
571                    // `extern_path` entry, which the pre-pass skips.
572                    let is_exact_override = effective_extern_paths
573                        .iter()
574                        .any(|(proto, _)| proto == &fqn);
575                    let module = if is_exact_override {
576                        extern_override_module(name, &rust_path, true)
577                    } else {
578                        nested_module_names
579                            .get(&fqn)
580                            .cloned()
581                            .unwrap_or_else(|| to_snake_case(name))
582                    };
583                    let parent_mod = if is_extern {
584                        match rust_path.rsplit_once("::") {
585                            Some((parent, _)) => format!("{parent}::{module}"),
586                            None => module,
587                        }
588                    } else {
589                        join_mod(&local_module, &module)
590                    };
591
592                    type_map.insert(fqn.clone(), rust_path);
593                    package_of.insert(fqn.clone(), package.to_string());
594                    register_nested_types(
595                        &mut type_map,
596                        &mut package_of,
597                        &mut nested_module_names,
598                        NestedRegistrationCtx {
599                            package,
600                            extern_paths: effective_extern_paths,
601                            type_name_prefix: &config.type_name_prefix,
602                        },
603                        &fqn,
604                        &parent_mod,
605                        msg,
606                    );
607                    register_nested_enum_closedness(
608                        &mut enum_closedness,
609                        &fqn,
610                        &file_features,
611                        msg,
612                    );
613                }
614            }
615
616            // Register top-level enums
617            for enum_type in &file.enum_type {
618                if let Some(name) = &enum_type.name {
619                    let fqn = format!("{}{}", proto_prefix, name);
620                    let (rust_path, _) = resolve_type_path(
621                        &fqn,
622                        name,
623                        file_root,
624                        &local_module,
625                        effective_extern_paths,
626                        &config.type_name_prefix,
627                    );
628                    type_map.insert(fqn.clone(), rust_path);
629                    package_of.insert(fqn.clone(), package.to_string());
630                    register_enum_closedness(&mut enum_closedness, &fqn, &file_features, enum_type);
631                }
632            }
633        }
634
635        // Plan field and oneof names up front so every emission site resolves
636        // the same Rust name for a member. Both plans' warnings are seeded
637        // into the sink now and drained with the rest after generation.
638        let (field_renames, oneof_keep_verbatim, mut plan_warnings) =
639            if config.idiomatic_field_names {
640                let plan = crate::field_names::plan_field_names(files);
641                (plan.field_renames, plan.oneof_keep_verbatim, plan.warnings)
642            } else {
643                (HashMap::new(), HashSet::new(), Vec::new())
644            };
645        let keyword_plan = crate::field_names::plan_keyword_escapes(
646            files,
647            config.idiomatic_field_names,
648            &field_renames,
649            &oneof_keep_verbatim,
650            generated_files,
651        );
652        plan_warnings.extend(keyword_plan.warnings);
653
654        Self {
655            files,
656            config,
657            denied_view_json: std::cell::OnceCell::new(),
658            guarded_reflection_messages: std::cell::OnceCell::new(),
659            type_map,
660            package_of,
661            enum_closedness,
662            // Only consulted by opened-enum default handling (a bare open
663            // enum can otherwise never have a non-zero first value), so the
664            // walk is skipped entirely for the default configuration.
665            enum_first_value: if config.has_enum_type_overrides() {
666                collect_enum_first_values(files)
667            } else {
668                HashMap::new()
669            },
670            deprecated_enum_values: std::cell::OnceCell::new(),
671            comment_map,
672            nested_module_names,
673            unboxed_oneof_variants,
674            inlined_message_fields,
675            table_plan: std::cell::OnceCell::new(),
676            field_renames,
677            oneof_keep_verbatim,
678            keyword_field_renames: keyword_plan.field_renames,
679            keyword_oneof_renames: keyword_plan.oneof_renames,
680            warnings: std::cell::RefCell::new(plan_warnings),
681            imports: std::cell::RefCell::new(crate::imports::ImportsPhase::Off),
682        }
683    }
684
685    /// The Rust source name for a proto field, before
686    /// [`make_field_ident`](crate::idents::make_field_ident) escapes it.
687    ///
688    /// With `idiomatic_field_names` off this is the proto name verbatim.
689    /// With it on, the name is snake_case-converted, unless the collision
690    /// plan recorded an exception for `(name, number)`. In both modes, a
691    /// rename that the keyword-escape plan recorded for `(name, number)`
692    /// replaces the result; such a name (`self__`) needs no escaping. See
693    /// [`crate::field_names`].
694    pub(crate) fn field_rust_name<'n>(&'n self, name: &'n str, number: i32) -> Cow<'n, str> {
695        if !self.keyword_field_renames.is_empty() {
696            if let Some(renamed) = self.keyword_field_renames.get(&(name.to_string(), number)) {
697                return Cow::Borrowed(renamed.as_str());
698            }
699        }
700        crate::field_names::planned_field_name(
701            self.config.idiomatic_field_names,
702            &self.field_renames,
703            name,
704            number,
705        )
706    }
707
708    /// The Rust field identifier for a proto field:
709    /// [`field_rust_name`](Self::field_rust_name) plus keyword escaping.
710    pub(crate) fn field_ident(&self, name: &str, number: i32) -> proc_macro2::Ident {
711        crate::idents::make_field_ident(&self.field_rust_name(name, number))
712    }
713
714    /// The Rust source name for a oneof, before
715    /// [`make_field_ident`](crate::idents::make_field_ident) escapes it.
716    ///
717    /// Mirrors [`field_rust_name`](Self::field_rust_name); a oneof whose
718    /// conversion collided keeps its verbatim proto name.
719    pub(crate) fn oneof_rust_name<'n>(&'n self, name: &'n str) -> Cow<'n, str> {
720        if !self.keyword_oneof_renames.is_empty() {
721            if let Some(renamed) = self.keyword_oneof_renames.get(name) {
722                return Cow::Borrowed(renamed.as_str());
723            }
724        }
725        crate::field_names::planned_oneof_name(
726            self.config.idiomatic_field_names,
727            &self.oneof_keep_verbatim,
728            name,
729        )
730    }
731
732    /// The Rust field identifier for a oneof:
733    /// [`oneof_rust_name`](Self::oneof_rust_name) plus keyword escaping.
734    pub(crate) fn oneof_ident(&self, name: &str) -> proc_macro2::Ident {
735        crate::idents::make_field_ident(&self.oneof_rust_name(name))
736    }
737
738    /// Doc note for a field whose Rust name was adjusted to resolve a
739    /// collision. Returns `None` when neither plan adjusted the name; the
740    /// ``Field N: `name` `` doc tag then gives the proto name.
741    pub(crate) fn field_rename_note(&self, name: &str, number: i32) -> Option<String> {
742        if !self.keyword_field_renames.is_empty() {
743            if let Some(resolved) = self.keyword_field_renames.get(&(name.to_string(), number)) {
744                return Some(keyword_rename_note("field", resolved));
745            }
746        }
747        if !self.config.idiomatic_field_names || self.field_renames.is_empty() {
748            return None;
749        }
750        let resolved = self.field_renames.get(&(name.to_string(), number))?;
751        Some(format!(
752            " Note: the snake_case conversion of `{name}` collides with another \
753             member of this message; the Rust name was adjusted to `{resolved}` \
754             (`_f<n>` suffixes carry the field number)."
755        ))
756    }
757
758    /// Doc note for a oneof that the keyword-escape plan renamed; `None` for
759    /// every other oneof.
760    pub(crate) fn oneof_rename_note(&self, name: &str) -> Option<String> {
761        let resolved = self.keyword_oneof_renames.get(name)?;
762        Some(keyword_rename_note("oneof", resolved))
763    }
764
765    /// `#[allow(non_snake_case)]` when any of `msg`'s emitted member names —
766    /// non-oneof-member fields and real oneofs, after `idiomatic_field_names`
767    /// resolution — contains an uppercase character (the rustc lint's
768    /// trigger; proto identifiers are ASCII). Empty for conforming messages,
769    /// so their generated output is unchanged.
770    ///
771    /// Applied at the struct and impl level (struct declarations and the
772    /// setter / `Deserialize` / `has_*` / owned-view-wrapper impls) rather
773    /// than per member, so it covers the pub fields *and* every method and
774    /// local whose name derives from them. Detection is independent of
775    /// `idiomatic_field_names`: a verbatim camelCase proto compiled with the
776    /// option off gets the same scoped allows, keeping consumer crates
777    /// warning-free either way.
778    pub(crate) fn message_non_snake_attr(&self, msg: &DescriptorProto) -> proc_macro2::TokenStream {
779        let non_snake = |s: &str| s.contains(|c: char| c.is_ascii_uppercase());
780        let mut real_oneofs: HashSet<i32> = HashSet::new();
781        let mut found = false;
782        for field in &msg.field {
783            let Some(name) = field.name.as_deref() else {
784                continue;
785            };
786            // Mirrors `impl_message::is_real_oneof_member` (not imported to
787            // keep context.rs free of emission-module dependencies).
788            if field.oneof_index.is_some() && !field.proto3_optional.unwrap_or(false) {
789                if let Some(idx) = field.oneof_index {
790                    real_oneofs.insert(idx);
791                }
792                continue;
793            }
794            if non_snake(&self.field_rust_name(name, field.number.unwrap_or(0))) {
795                found = true;
796                break;
797            }
798        }
799        if !found {
800            for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
801                let Some(name) = oneof.name.as_deref() else {
802                    continue;
803                };
804                if !real_oneofs.contains(&i32::try_from(idx).unwrap_or(i32::MAX)) {
805                    continue;
806                }
807                if non_snake(&self.oneof_rust_name(name)) {
808                    found = true;
809                    break;
810                }
811            }
812        }
813        if found {
814            quote::quote! { #[allow(non_snake_case)] }
815        } else {
816            proc_macro2::TokenStream::new()
817        }
818    }
819
820    /// Record a non-fatal diagnostic to surface as a build warning.
821    pub(crate) fn warn(&self, warning: crate::CodeGenWarning) {
822        self.warnings.borrow_mut().push(warning);
823    }
824
825    /// Drain the diagnostics accumulated during generation.
826    ///
827    /// `pub(crate)` so it can only be called from [`generate_with_diagnostics`]
828    /// after all packages are generated — draining mid-flight would truncate the
829    /// diagnostic stream.
830    pub(crate) fn take_warnings(&self) -> Vec<crate::CodeGenWarning> {
831        self.warnings.take()
832    }
833
834    /// Truncate the warning sink back to `len` entries.
835    ///
836    /// Used by the `idiomatic_imports` collection pass, whose dry-run
837    /// generation would otherwise record every diagnostic twice.
838    pub(crate) fn truncate_warnings(&self, len: usize) {
839        self.warnings.borrow_mut().truncate(len);
840    }
841
842    /// The number of warnings recorded so far (a mark for
843    /// [`truncate_warnings`](Self::truncate_warnings)).
844    pub(crate) fn warnings_len(&self) -> usize {
845        self.warnings.borrow().len()
846    }
847
848    /// Look up the proto package that owns a fully-qualified type name.
849    ///
850    /// `proto_fqn` is the leading-dot form (e.g. `.my.pkg.MyMessage`).
851    /// Returns `None` when the type is not in the descriptor set.
852    pub(crate) fn package_of(&self, proto_fqn: &str) -> Option<&str> {
853        self.package_of.get(proto_fqn).map(String::as_str)
854    }
855
856    // ── Package-root import registry (idiomatic_imports) ────────────────
857
858    /// Enter the collection phase: subsequent package-root path
859    /// resolutions are recorded instead of shortened.
860    pub(crate) fn imports_begin_collecting(&self) {
861        *self.imports.borrow_mut() =
862            crate::imports::ImportsPhase::Collecting(std::collections::BTreeSet::new());
863    }
864
865    /// Leave the collection phase, returning the recorded paths.
866    pub(crate) fn imports_take_collected(&self) -> std::collections::BTreeSet<String> {
867        match self.imports.replace(crate::imports::ImportsPhase::Off) {
868            crate::imports::ImportsPhase::Collecting(set) => set,
869            _ => std::collections::BTreeSet::new(),
870        }
871    }
872
873    /// Enter the resolution phase with assigned bindings.
874    pub(crate) fn imports_set_resolving(&self, imports: crate::imports::RootImports) {
875        *self.imports.borrow_mut() = crate::imports::ImportsPhase::Resolving(imports);
876    }
877
878    /// Reset to [`ImportsPhase::Off`] after a package is generated, so
879    /// state never leaks into the next package.
880    ///
881    /// [`ImportsPhase::Off`]: crate::imports::ImportsPhase::Off
882    pub(crate) fn imports_reset(&self) {
883        *self.imports.borrow_mut() = crate::imports::ImportsPhase::Off;
884    }
885
886    /// The `use` block backing the current package's assigned short names
887    /// (empty unless in the resolution phase).
888    pub(crate) fn imports_use_block(&self) -> proc_macro2::TokenStream {
889        match &*self.imports.borrow() {
890            crate::imports::ImportsPhase::Resolving(imports) => imports.use_items(),
891            _ => proc_macro2::TokenStream::new(),
892        }
893    }
894
895    /// Route a package-root type path through the import registry.
896    ///
897    /// `nesting` is the emitting scope's module depth below the package
898    /// root; only depth-0 emissions land in the package-root scope where
899    /// the `use` block is visible, so anything deeper passes through
900    /// unchanged — as does everything when the registry is off.
901    fn root_path(&self, path: String, nesting: usize) -> String {
902        if nesting != 0 {
903            return path;
904        }
905        match &mut *self.imports.borrow_mut() {
906            crate::imports::ImportsPhase::Off => path,
907            crate::imports::ImportsPhase::Collecting(set) => {
908                if crate::imports::shortenable(&path) {
909                    set.insert(path.clone());
910                }
911                path
912            }
913            crate::imports::ImportsPhase::Resolving(imports) => match imports.resolve(&path) {
914                Some(short) => short.to_string(),
915                None => path,
916            },
917        }
918    }
919
920    /// Route a runtime/prelude type's canonical qualified path through the
921    /// import registry, returning the tokens to emit.
922    ///
923    /// Same depth-0 gating as [`root_path`](Self::root_path); `canonical`
924    /// must be one of the `RUNTIME_IMPORTS` paths in `imports.rs`.
925    pub(crate) fn root_runtime_path(
926        &self,
927        canonical: &str,
928        nesting: usize,
929    ) -> proc_macro2::TokenStream {
930        crate::idents::rust_path_to_tokens(&self.root_path(canonical.to_string(), nesting))
931    }
932
933    /// Returns the name of the module that holds the nested types of a
934    /// top-level message.
935    ///
936    /// `package` is the proto package (empty for none), `name` the message's
937    /// proto name. The module is `snake_case(name)`, with `_` appended until
938    /// the name is free when it is taken in the package: `oof_` when
939    /// `message Oof` is beside `package <pkg>.oof` (issue #135), `item_` for
940    /// `message item`, whose struct has the module's name, and `crate_`,
941    /// `arbitrary_` and `oneof_` for `message Crate`, `message Arbitrary` and
942    /// `message Oneof`. Both emission and reference resolution use this
943    /// value, so they agree.
944    ///
945    /// Returns `snake_case(name)` for a name that is not a top-level message
946    /// of `package`, and for a message that has a per-type `extern_path`
947    /// entry.
948    pub fn nested_module_name(&self, package: &str, name: &str) -> String {
949        if package.is_empty() {
950            self.message_module_name(name)
951        } else {
952            self.message_module_name(&format!("{package}.{name}"))
953        }
954    }
955
956    /// Returns the name of the module that holds the nested types of the
957    /// message `proto_fqn`, at any nesting level. The rule is that of
958    /// [`nested_module_name`](Self::nested_module_name), applied in the scope
959    /// that declares the message: its package, or its enclosing message.
960    ///
961    /// `proto_fqn` is the dotless form (`"pkg.Outer.Inner"`).
962    pub(crate) fn message_module_name(&self, proto_fqn: &str) -> String {
963        self.nested_module_names
964            .get(&format!(".{proto_fqn}"))
965            .cloned()
966            .unwrap_or_else(|| to_snake_case(proto_fqn.rsplit('.').next().unwrap_or(proto_fqn)))
967    }
968
969    /// Build a context matching what [`generate()`](crate::generate) uses
970    /// internally.
971    ///
972    /// Computes effective extern paths (user-provided + auto-injected WKT
973    /// mapping to `buffa-types` + auto-injected `descriptor.proto` /
974    /// `compiler/plugin.proto` file-level mapping to `buffa-descriptor`) and
975    /// builds the type map from them.
976    ///
977    /// Convenience for downstream generators (e.g. `connectrpc-codegen`)
978    /// that emit code alongside buffa's message types and need identical
979    /// type-path resolution. Using this instead of [`new()`](Self::new) +
980    /// manual extern-path computation ensures zero drift with buffa's own
981    /// generation.
982    pub fn for_generate(
983        files: &'a [FileDescriptorProto],
984        files_to_generate: &[String],
985        config: &'a CodeGenConfig,
986    ) -> Self {
987        let paths = crate::effective_extern_paths(files, files_to_generate, config);
988        let file_paths = crate::effective_file_extern_paths(files_to_generate, config);
989        let generated_files: HashSet<String> = files_to_generate.iter().cloned().collect();
990        Self::with_extern_resolution(files, config, &paths, &file_paths, Some(&generated_files))
991    }
992
993    /// Look up the Rust type path for a fully-qualified protobuf type name.
994    pub fn rust_type(&self, proto_fqn: &str) -> Option<&str> {
995        self.type_map.get(proto_fqn).map(|s| s.as_str())
996    }
997
998    /// Look up the source comment for a protobuf element by FQN.
999    ///
1000    /// `fqn` uses the same dotted form as `proto_fqn` throughout codegen
1001    /// (no leading dot). For sub-elements, append the element name:
1002    /// - Message: `"pkg.Message"`
1003    /// - Field: `"pkg.Message.field_name"`
1004    /// - Enum value: `"pkg.Enum.VALUE_NAME"`
1005    /// - Oneof: `"pkg.Message.oneof_name"`
1006    pub fn comment(&self, fqn: &str) -> Option<&str> {
1007        self.comment_map.get(fqn).map(|s| s.as_str())
1008    }
1009
1010    /// Look up whether an enum (by fully-qualified proto name) is closed.
1011    ///
1012    /// Returns `None` if the enum is not in this compilation set (e.g., an
1013    /// extern_path type), in which case callers should fall back to the
1014    /// referencing field's feature chain (correct for proto2/proto3 where
1015    /// `enum_type` is file-level anyway).
1016    pub fn is_enum_closed(&self, proto_fqn: &str) -> Option<bool> {
1017        self.enum_closedness.get(proto_fqn).copied()
1018    }
1019
1020    /// Look up an enum's first declared value number — its implicit default
1021    /// per spec. `None` for enums not in this compilation set (extern_path).
1022    pub(crate) fn enum_first_value(&self, proto_fqn: &str) -> Option<i32> {
1023        self.enum_first_value.get(proto_fqn).copied()
1024    }
1025
1026    /// Whether the generated item for the enum value `value_name` of enum
1027    /// `proto_fqn` is `#[deprecated]`, by the rule in
1028    /// [`deprecated_items`](crate::enumeration::deprecated_items).
1029    /// `proto_fqn` is the dotted form used by
1030    /// `FieldDescriptorProto::type_name` (`.pkg.Enum`, `.pkg.Msg.Nested`).
1031    ///
1032    /// Enums imported from a dependency file are in `files` along with the
1033    /// compilation set's own, so an `extern_path` remap still resolves here and
1034    /// this build emits its own guard — the remapped Rust type is a different
1035    /// item whose deprecation state we cannot see, and a missing guard would
1036    /// only warn inside the other crate's generated code.
1037    pub(crate) fn enum_value_is_deprecated(&self, proto_fqn: &str, value_name: &str) -> bool {
1038        self.deprecated_enum_values
1039            .get_or_init(|| collect_deprecated_enum_values(self.files))
1040            .get(proto_fqn)
1041            .is_some_and(|names| names.contains(value_name))
1042    }
1043
1044    /// Look up the Rust type path relative to the current code generation
1045    /// scope.
1046    ///
1047    /// `current_package` is the proto package (e.g., `"google.protobuf"`).
1048    /// `nesting` is the number of message module levels the generated code
1049    /// sits inside (0 for struct fields and impls at the package level,
1050    /// 1 for oneof enums inside a message module, etc.).
1051    ///
1052    /// - **Same package**: strips the package prefix and prepends `super::`
1053    ///   for each nesting level.
1054    /// - **Cross package (local)**: navigates via `super::` to the common
1055    ///   ancestor, then descends into the target package. This works
1056    ///   regardless of where the module tree is placed in the user's crate.
1057    /// - **Cross package (extern)**: returns the absolute extern path as-is.
1058    pub fn rust_type_relative(
1059        &self,
1060        proto_fqn: &str,
1061        current_package: &str,
1062        nesting: usize,
1063    ) -> Option<String> {
1064        let full_path = self.type_map.get(proto_fqn)?;
1065
1066        // Extern types use absolute paths (starting with `::` or `crate::`)
1067        // and need no relative resolution — they work from any module position.
1068        if full_path.starts_with("::") || full_path.starts_with("crate::") {
1069            return Some(self.root_path(full_path.clone(), nesting));
1070        }
1071
1072        let target_package = self
1073            .package_of
1074            .get(proto_fqn)
1075            .map(|s| s.as_str())
1076            .unwrap_or("");
1077
1078        // Extract the type's path within its package (everything after the
1079        // package module prefix).
1080        let target_rust_module = target_package.replace('.', "::");
1081        let type_suffix = if target_rust_module.is_empty() {
1082            full_path.as_str()
1083        } else {
1084            full_path
1085                .strip_prefix(&format!("{}::", target_rust_module))
1086                .unwrap_or(full_path)
1087        };
1088
1089        if current_package == target_package {
1090            // Same package — just the type suffix, with super:: for nesting.
1091            if nesting == 0 {
1092                return Some(type_suffix.to_string());
1093            }
1094            let supers = (0..nesting).map(|_| "super").collect::<Vec<_>>().join("::");
1095            return Some(format!("{}::{}", supers, type_suffix));
1096        }
1097
1098        // Cross-package local type: compute a super::-based relative path.
1099        let current_parts: Vec<&str> = if current_package.is_empty() {
1100            vec![]
1101        } else {
1102            current_package.split('.').collect()
1103        };
1104        let target_parts: Vec<&str> = if target_package.is_empty() {
1105            vec![]
1106        } else {
1107            target_package.split('.').collect()
1108        };
1109
1110        // Find the length of the common package prefix.
1111        let common_len = current_parts
1112            .iter()
1113            .zip(&target_parts)
1114            .take_while(|(a, b)| a == b)
1115            .count();
1116
1117        // Navigate up: one super:: per remaining current package segment,
1118        // plus one per nesting level (message module depth).
1119        let up_count = (current_parts.len() - common_len) + nesting;
1120
1121        // Navigate down: target package segments beyond the common prefix.
1122        let down_parts = &target_parts[common_len..];
1123
1124        let mut segments: Vec<&str> = vec!["super"; up_count];
1125        segments.extend_from_slice(down_parts);
1126
1127        // Append the type's within-package path.
1128        let mut result = segments.join("::");
1129        if !result.is_empty() {
1130            result.push_str("::");
1131        }
1132        result.push_str(type_suffix);
1133
1134        Some(self.root_path(result, nesting))
1135    }
1136
1137    /// Like [`rust_type_relative`](Self::rust_type_relative) but returns the
1138    /// path split at the target-package boundary.
1139    ///
1140    /// Ancillary kinds (views, oneof enums) live in the `__buffa::<kind>::`
1141    /// sub-tree of each package; callers compose the final path as
1142    /// `to_package + "::__buffa::" + <kind> + "::" + within_package`.
1143    ///
1144    /// `nesting` is the **total** module depth of the caller's emission
1145    /// scope below the current package root — i.e. message-nesting plus any
1146    /// `__buffa::<kind>::` levels the caller is already inside (0 for owned
1147    /// types, +2 for `__buffa::view::`, +3 for `__buffa::view::oneof::`).
1148    pub fn rust_type_relative_split(
1149        &self,
1150        proto_fqn: &str,
1151        current_package: &str,
1152        nesting: usize,
1153    ) -> Option<SplitPath> {
1154        let full_path = self.type_map.get(proto_fqn)?;
1155
1156        let target_package = self
1157            .package_of
1158            .get(proto_fqn)
1159            .map(|s| s.as_str())
1160            .unwrap_or("");
1161
1162        // Compute the type's path within its package (everything after the
1163        // package module prefix). For extern types the prefix is the
1164        // configured rust_module (e.g. `::buffa_types::google::protobuf`),
1165        // not the bare dotted package, so derive it the same way `new()`
1166        // populated the map.
1167        let target_rust_module = if full_path.starts_with("::") || full_path.starts_with("crate::")
1168        {
1169            // Reconstruct the extern module prefix by stripping the
1170            // within-package suffix length. We know the proto FQN's
1171            // within-package portion (FQN minus package), so the full_path's
1172            // last N segments correspond to it.
1173            //
1174            // Simpler: re-derive via `resolve_extern_prefix` would need the
1175            // original extern_paths list. Instead, compute within-package
1176            // from the proto FQN (which we know) and slice full_path.
1177            let fqn_no_dot = proto_fqn.strip_prefix('.').unwrap_or(proto_fqn);
1178            let within_proto = if target_package.is_empty() {
1179                fqn_no_dot
1180            } else {
1181                fqn_no_dot
1182                    .strip_prefix(target_package)
1183                    .and_then(|s| s.strip_prefix('.'))
1184                    .unwrap_or(fqn_no_dot)
1185            };
1186            // within_proto is dotted (e.g. "Outer.Inner"); within full_path
1187            // it's `outer::Inner` (snake_case modules + final PascalCase).
1188            // Count the segments and strip that many from full_path to recover
1189            // the module the type lives in.
1190            //
1191            // For paths buffa builds itself (`<rust_module>::<within>`) and for
1192            // per-type `extern_path` overrides whose target mirrors the proto
1193            // nesting (the sensible case — e.g. mapping to another
1194            // buffa-generated crate), `full_segs.len() >= within_segs`. A
1195            // pathological override that maps a deeply-nested type to a shorter
1196            // Rust path can't have a matching `__buffa::` view/oneof tree
1197            // anyway, so we clamp with `saturating_sub` rather than panic and
1198            // let the (unresolvable) reference surface as a normal compile error.
1199            let within_segs = within_proto.split('.').count();
1200            let full_segs: Vec<&str> = full_path.split("::").collect();
1201            let cut = full_segs.len().saturating_sub(within_segs);
1202            full_segs[..cut].join("::")
1203        } else {
1204            target_package.replace('.', "::")
1205        };
1206
1207        let type_suffix = if target_rust_module.is_empty() {
1208            full_path.as_str()
1209        } else {
1210            full_path
1211                .strip_prefix(&format!("{}::", target_rust_module))
1212                .unwrap_or(full_path)
1213        };
1214
1215        // Extern: absolute path; nesting irrelevant.
1216        if full_path.starts_with("::") || full_path.starts_with("crate::") {
1217            return Some(SplitPath {
1218                to_package: target_rust_module,
1219                within_package: type_suffix.to_string(),
1220                is_extern: true,
1221            });
1222        }
1223
1224        if current_package == target_package {
1225            let to_package = if nesting == 0 {
1226                String::new()
1227            } else {
1228                (0..nesting).map(|_| "super").collect::<Vec<_>>().join("::")
1229            };
1230            return Some(SplitPath {
1231                to_package,
1232                within_package: type_suffix.to_string(),
1233                is_extern: false,
1234            });
1235        }
1236
1237        // Cross-package local.
1238        let current_parts: Vec<&str> = if current_package.is_empty() {
1239            vec![]
1240        } else {
1241            current_package.split('.').collect()
1242        };
1243        let target_parts: Vec<&str> = if target_package.is_empty() {
1244            vec![]
1245        } else {
1246            target_package.split('.').collect()
1247        };
1248        let common_len = current_parts
1249            .iter()
1250            .zip(&target_parts)
1251            .take_while(|(a, b)| a == b)
1252            .count();
1253        let up_count = (current_parts.len() - common_len) + nesting;
1254        let down_parts = &target_parts[common_len..];
1255
1256        let mut segments: Vec<&str> = vec!["super"; up_count];
1257        segments.extend_from_slice(down_parts);
1258
1259        Some(SplitPath {
1260            to_package: segments.join("::"),
1261            within_package: type_suffix.to_string(),
1262            is_extern: false,
1263        })
1264    }
1265
1266    /// Collect custom attributes matching a fully-qualified proto path.
1267    ///
1268    /// Returns a `TokenStream` of all `#[...]` attributes whose path prefix
1269    /// matches `fqn`. Each attribute string must parse as one or more outer
1270    /// attributes (`syn::Attribute::parse_outer`) with no tokens left over,
1271    /// so the caller can interpolate the result directly into `quote!`.
1272    ///
1273    /// `fqn` uses dotted form without a leading dot (e.g., `"my.pkg.MyMessage"`).
1274    ///
1275    /// # Errors
1276    ///
1277    /// Returns `CodeGenError::InvalidCustomAttribute` if any matching attribute
1278    /// string does not parse as one or more `#[...]` attributes.
1279    pub(crate) fn matching_attributes(
1280        attrs: &[(String, String)],
1281        fqn: &str,
1282    ) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
1283        if attrs.is_empty() {
1284            return Ok(proc_macro2::TokenStream::new());
1285        }
1286        let fqn_dotted = format!(".{fqn}");
1287        let mut tokens = proc_macro2::TokenStream::new();
1288        for (prefix, attr_str) in attrs {
1289            if matches_proto_prefix(prefix, &fqn_dotted) {
1290                tokens.extend(parse_custom_attribute(prefix, attr_str)?);
1291            }
1292        }
1293        Ok(tokens)
1294    }
1295
1296    /// Resolve the [`BytesRepr`](crate::BytesRepr) for a `bytes` field at the
1297    /// given proto path.
1298    ///
1299    /// `field_fqn` is the fully-qualified proto field path, e.g.,
1300    /// `".my.pkg.MyMessage.data"`. Rules in `config.bytes_fields` are matched
1301    /// using proto-segment-aware prefix matching (`"."` matches all,
1302    /// `".my.pkg"` matches `".my.pkg.Msg.data"` but not `".my.pkgs.X.data"`);
1303    /// the **last** matching rule wins, letting a specific override follow a
1304    /// broad default. Fields matching no rule use
1305    /// [`BytesRepr::Vec`](crate::BytesRepr::Vec).
1306    pub fn bytes_repr(&self, field_fqn: &str) -> crate::BytesRepr {
1307        self.config
1308            .bytes_fields
1309            .iter()
1310            .rev()
1311            .find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
1312            .map_or(crate::BytesRepr::default(), |(_, repr)| repr.clone())
1313    }
1314
1315    pub(crate) fn zeroizes_message(&self, msg_fqn: &str) -> bool {
1316        let dotted = if msg_fqn.starts_with('.') {
1317            Cow::Borrowed(msg_fqn)
1318        } else {
1319            Cow::Owned(format!(".{msg_fqn}"))
1320        };
1321        self.config.generate_zeroize
1322            || self
1323                .config
1324                .zeroize_messages
1325                .iter()
1326                .any(|prefix| matches_proto_prefix(prefix, &dotted))
1327    }
1328
1329    fn containing_messages(&self, selected: impl Fn(&str) -> bool) -> HashSet<String> {
1330        fn walk(
1331            messages: &[DescriptorProto],
1332            prefix: &str,
1333            edges: &mut Vec<(String, Vec<String>)>,
1334        ) {
1335            for message in messages {
1336                let Some(name) = message.name.as_deref() else {
1337                    continue;
1338                };
1339                let name = format!("{prefix}.{name}");
1340                let children = message
1341                    .field
1342                    .iter()
1343                    .filter(|field| {
1344                        matches!(field.r#type, Some(Type::TYPE_MESSAGE | Type::TYPE_GROUP))
1345                    })
1346                    .filter_map(|field| field.type_name.clone())
1347                    .collect();
1348                edges.push((name.clone(), children));
1349                walk(&message.nested_type, &name, edges);
1350            }
1351        }
1352        let mut edges = Vec::new();
1353        for file in self.files {
1354            let package = file.package.as_deref().unwrap_or_default();
1355            let prefix = if package.is_empty() {
1356                String::new()
1357            } else {
1358                format!(".{package}")
1359            };
1360            walk(&file.message_type, &prefix, &mut edges);
1361        }
1362        let mut denied = HashSet::new();
1363        let mut pending = Vec::new();
1364        let mut parents: HashMap<String, Vec<String>> = HashMap::new();
1365        for (name, children) in edges {
1366            for child in children {
1367                parents.entry(child).or_default().push(name.clone());
1368            }
1369            if selected(&name) {
1370                denied.insert(name.clone());
1371                pending.push(name);
1372            }
1373        }
1374        // Visit each denied node and ownership edge once. The visited set
1375        // terminates cycles without repeatedly scanning a large schema.
1376        while let Some(child) = pending.pop() {
1377            if let Some(containers) = parents.get(&child) {
1378                for parent in containers {
1379                    if denied.insert(parent.clone()) {
1380                        pending.push(parent.clone());
1381                    }
1382                }
1383            }
1384        }
1385        denied
1386    }
1387
1388    pub(crate) fn denies_view_json(&self, msg_fqn: &str) -> bool {
1389        if self.config.deny_view_json.is_empty() {
1390            return false;
1391        }
1392        let denied = self.denied_view_json.get_or_init(|| {
1393            self.containing_messages(|name| {
1394                self.config
1395                    .deny_view_json
1396                    .iter()
1397                    .any(|rule| matches_proto_prefix(rule, name))
1398            })
1399        });
1400        let name = if msg_fqn.starts_with('.') {
1401            Cow::Borrowed(msg_fqn)
1402        } else {
1403            Cow::Owned(format!(".{msg_fqn}"))
1404        };
1405        denied.contains(name.as_ref())
1406    }
1407
1408    pub(crate) fn contains_guarded_reflection(&self, msg_fqn: &str) -> bool {
1409        if !self.config.generate_reflection
1410            || (!self.config.generate_zeroize && self.config.zeroize_messages.is_empty())
1411        {
1412            return false;
1413        }
1414        let guarded = self
1415            .guarded_reflection_messages
1416            .get_or_init(|| self.containing_messages(|name| self.zeroizes_message(name)));
1417        let name = if msg_fqn.starts_with('.') {
1418            Cow::Borrowed(msg_fqn)
1419        } else {
1420            Cow::Owned(format!(".{msg_fqn}"))
1421        };
1422        guarded.contains(name.as_ref())
1423    }
1424
1425    /// Whether this message stores unknown fields.
1426    ///
1427    /// Starts from [`CodeGenConfig::preserve_unknown_fields`] and applies
1428    /// [`CodeGenConfig::preserve_unknown_fields_in`]; the **last** matching
1429    /// rule wins. Rules use proto-segment-aware prefix matching, so a rule
1430    /// naming a message also covers the messages nested inside it, while a
1431    /// rule naming a nested message does not cover its enclosing message.
1432    /// `msg_fqn` is the message's proto path, with or without a leading dot
1433    /// (`"pkg.Msg"` or `".pkg.Msg"`).
1434    pub fn preserve_unknown_fields(&self, msg_fqn: &str) -> bool {
1435        let rules = &self.config.preserve_unknown_fields_in;
1436        if rules.is_empty() {
1437            return self.config.preserve_unknown_fields;
1438        }
1439        let dotted = if msg_fqn.starts_with('.') {
1440            Cow::Borrowed(msg_fqn)
1441        } else {
1442            Cow::Owned(format!(".{msg_fqn}"))
1443        };
1444        rules
1445            .iter()
1446            .rev()
1447            .find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
1448            .map_or(self.config.preserve_unknown_fields, |(_, enabled)| *enabled)
1449    }
1450
1451    /// The last [`CodeGenConfig::codec_strategy_in`] rule that covers this
1452    /// message, if any: the rule that decided its strategy, as opposed to the
1453    /// global default. `msg_fqn` is the message's proto path, with or without
1454    /// a leading dot.
1455    pub(crate) fn codec_strategy_rule(
1456        &self,
1457        msg_fqn: &str,
1458    ) -> Option<&'a (String, crate::CodecStrategy)> {
1459        let dotted = if msg_fqn.starts_with('.') {
1460            Cow::Borrowed(msg_fqn)
1461        } else {
1462            Cow::Owned(format!(".{msg_fqn}"))
1463        };
1464        self.config
1465            .codec_strategy_in
1466            .iter()
1467            .rev()
1468            .find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
1469    }
1470
1471    /// The codec strategy requested for this message.
1472    ///
1473    /// Starts from [`CodeGenConfig::codec_strategy`] and applies
1474    /// [`CodeGenConfig::codec_strategy_in`]; the **last** matching rule wins.
1475    /// This is what was asked for, and a message that cannot use
1476    /// [`CodecStrategy::Table`] still gets it here: whether it does is
1477    /// [`uses_table_codec`](Self::uses_table_codec).
1478    pub(crate) fn codec_strategy(&self, msg_fqn: &str) -> crate::CodecStrategy {
1479        self.codec_strategy_rule(msg_fqn)
1480            .map_or(self.config.codec_strategy, |(_, strategy)| *strategy)
1481    }
1482
1483    /// Whether any message may be asked for the table codec, so that
1484    /// [`plan_table_codec`](Self::plan_table_codec) has work to do.
1485    pub(crate) fn table_codec_requested(&self) -> bool {
1486        self.config.codec_strategy == crate::CodecStrategy::Table
1487            || self
1488                .config
1489                .codec_strategy_in
1490                .iter()
1491                .any(|(_, s)| *s == crate::CodecStrategy::Table)
1492    }
1493
1494    /// Decide which messages use the table codec. Call once, after
1495    /// construction, when [`table_codec_requested`](Self::table_codec_requested)
1496    /// is true; warnings go to the diagnostics sink.
1497    ///
1498    /// # Errors
1499    ///
1500    /// Returns an error for a `codec_strategy_in` rule that names, by its exact
1501    /// path, a message that cannot use the table codec.
1502    pub(crate) fn plan_table_codec(
1503        &self,
1504        files: &[crate::generated::descriptor::FileDescriptorProto],
1505        files_to_generate: &[String],
1506    ) -> Result<(), crate::CodeGenError> {
1507        let (plan, warnings) = crate::table_plan::plan(self, files, files_to_generate)?;
1508        for w in warnings {
1509            self.warn(w);
1510        }
1511        let planned = self.table_plan.set(plan);
1512        debug_assert!(planned.is_ok(), "the table codec is planned once per run");
1513        Ok(())
1514    }
1515
1516    /// Whether this message is generated with the table codec.
1517    /// `msg_fqn` is the message's proto path, with or without a leading dot.
1518    pub(crate) fn uses_table_codec(&self, msg_fqn: &str) -> bool {
1519        let Some(plan) = self.table_plan.get() else {
1520            return false;
1521        };
1522        if msg_fqn.starts_with('.') {
1523            plan.contains(msg_fqn)
1524        } else {
1525            plan.contains(&format!(".{msg_fqn}"))
1526        }
1527    }
1528
1529    /// Whether this message's generated JSON deserializer rejects unknown
1530    /// fields.
1531    ///
1532    /// Starts from [`CodeGenConfig::deny_unknown_json_fields`] and applies
1533    /// [`CodeGenConfig::deny_unknown_json_fields_in`]; the **last** matching
1534    /// rule wins. Matching follows the same proto-segment-aware prefix rules
1535    /// as [`preserve_unknown_fields`](Self::preserve_unknown_fields), so a
1536    /// rule naming a message also covers the messages nested inside it, while
1537    /// a rule naming a nested message does not cover its enclosing message.
1538    /// `msg_fqn` is the message's proto path, with or without a leading dot.
1539    pub fn deny_unknown_json_fields(&self, msg_fqn: &str) -> bool {
1540        let rules = &self.config.deny_unknown_json_fields_in;
1541        if rules.is_empty() {
1542            return self.config.deny_unknown_json_fields;
1543        }
1544        let dotted = if msg_fqn.starts_with('.') {
1545            Cow::Borrowed(msg_fqn)
1546        } else {
1547            Cow::Owned(format!(".{msg_fqn}"))
1548        };
1549        rules
1550            .iter()
1551            .rev()
1552            .find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
1553            .map_or(self.config.deny_unknown_json_fields, |(_, enabled)| {
1554                *enabled
1555            })
1556    }
1557
1558    /// Whether a [`skip_debug`](crate::CodeGenConfig::skip_debug) rule covers
1559    /// the message at `message_fqn`, so that the generated `Debug` impls of
1560    /// the message and of its oneof enums are omitted.
1561    ///
1562    /// Rules use the same proto-segment-aware prefix matching as
1563    /// [`preserve_unknown_fields`](Self::preserve_unknown_fields): a rule
1564    /// naming a message also covers the messages nested inside it, and `"."`
1565    /// matches every message. Enums are matched by
1566    /// [`skip_debug_enum`](Self::skip_debug_enum).
1567    pub fn skip_debug(&self, message_fqn: &str) -> bool {
1568        if self.config.skip_debug.is_empty() {
1569            return false;
1570        }
1571        let dotted = if message_fqn.starts_with('.') {
1572            Cow::Borrowed(message_fqn)
1573        } else {
1574            Cow::Owned(format!(".{message_fqn}"))
1575        };
1576        self.config
1577            .skip_debug
1578            .iter()
1579            .any(|prefix| matches_proto_prefix(prefix, &dotted))
1580    }
1581
1582    /// Whether a [`skip_debug`](crate::CodeGenConfig::skip_debug) rule names
1583    /// the enum at `enum_fqn`, so that its derived `Debug` is omitted.
1584    ///
1585    /// The match is exact. A rule for an enclosing message or package leaves
1586    /// the enum's derive in place, because `buffa::Enumeration` requires
1587    /// `Debug` and an enum without it compiles only once the consuming crate
1588    /// implements it.
1589    pub fn skip_debug_enum(&self, enum_fqn: &str) -> bool {
1590        let name = enum_fqn.strip_prefix('.').unwrap_or(enum_fqn);
1591        self.config
1592            .skip_debug
1593            .iter()
1594            .any(|rule| rule.strip_prefix('.') == Some(name))
1595    }
1596
1597    /// Check whether a message-typed oneof variant at the given proto path is
1598    /// stored inline (opted out of `Box` wrapping).
1599    ///
1600    /// `variant_fqn` is the fully-qualified variant path, e.g.
1601    /// `".my.pkg.MyMessage.body.small"`. This consults the set resolved at
1602    /// context construction by the internal `resolve_unboxed_variants` pass,
1603    /// not the raw config rules: recursive variants matched only by a prefix
1604    /// rule are excluded there (they stay boxed), so every codegen site that
1605    /// asks agrees with the emitted enum declaration.
1606    pub fn oneof_unboxed(&self, variant_fqn: &str) -> bool {
1607        self.unboxed_oneof_variants.contains(variant_fqn)
1608    }
1609
1610    /// Resolve the [`StringRepr`](crate::StringRepr) for a `string` field at the
1611    /// given proto path.
1612    ///
1613    /// `field_fqn` is the fully-qualified proto field path, e.g.
1614    /// `".my.pkg.MyMessage.name"`. Rules in `config.string_fields` are matched
1615    /// with the same proto-segment-aware prefix logic as
1616    /// [`bytes_repr`](Self::bytes_repr); the **last** matching rule wins,
1617    /// letting a specific override follow a broad default. Fields matching no
1618    /// rule use [`StringRepr::String`](crate::StringRepr::String).
1619    /// Whether the custom representation `rust_type` is listed in
1620    /// [`json_policy_types`](CodeGenConfig::json_policy_types) and JSON is
1621    /// generated.
1622    pub(crate) fn is_json_policy_type(&self, rust_type: &str) -> bool {
1623        if !self.config.generate_json || self.config.json_policy_types.is_empty() {
1624            return false;
1625        }
1626        let key = rust_type_key(rust_type);
1627        self.config
1628            .json_policy_types
1629            .iter()
1630            .any(|listed| rust_type_key(listed) == key)
1631    }
1632
1633    pub fn string_repr(&self, field_fqn: &str) -> crate::StringRepr {
1634        self.config
1635            .string_fields
1636            .iter()
1637            .rev()
1638            .find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
1639            .map_or(crate::StringRepr::default(), |(_, repr)| repr.clone())
1640    }
1641
1642    /// Resolve the [`MapRepr`](crate::MapRepr) for a `map` field at the given
1643    /// proto path.
1644    ///
1645    /// `field_fqn` is the fully-qualified proto field path, e.g.
1646    /// `".my.pkg.MyMessage.entries"`. Rules in `config.map_fields` are matched
1647    /// with the same proto-segment-aware prefix logic as
1648    /// [`string_repr`](Self::string_repr); the **last** matching rule wins,
1649    /// letting a specific override follow a broad default. Fields matching no
1650    /// rule use [`MapRepr::HashMap`](crate::MapRepr::HashMap).
1651    pub fn map_repr(&self, field_fqn: &str) -> crate::MapRepr {
1652        self.config
1653            .map_fields
1654            .iter()
1655            .rev()
1656            .find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
1657            .map_or_else(
1658                || {
1659                    if field_fqn
1660                        .rsplit_once('.')
1661                        .is_some_and(|(message, _)| self.zeroizes_message(message))
1662                    {
1663                        crate::MapRepr::Custom("::buffa::sensitive::Map".into())
1664                    } else {
1665                        crate::MapRepr::default()
1666                    }
1667                },
1668                |(_, repr)| repr.clone(),
1669            )
1670    }
1671
1672    /// Resolve the [`PointerRepr`](crate::PointerRepr) for a singular message
1673    /// field at the given proto path. Last matching rule wins (proto-segment
1674    /// prefix match); fields matching no rule use
1675    /// [`PointerRepr::Box`](crate::PointerRepr::Box).
1676    ///
1677    /// `Inline` is recursion-aware: a path whose raw rule resolves to
1678    /// [`PointerRepr::Inline`](crate::PointerRepr::Inline) but is absent from
1679    /// the precomputed `inlined_message_fields` set
1680    /// (a recursive singular field, or a non-singular path such as a oneof
1681    /// variant) is demoted to `Box` so the generated type stays sized.
1682    pub fn pointer_repr(&self, field_fqn: &str) -> crate::PointerRepr {
1683        let raw = self
1684            .config
1685            .pointer_fields
1686            .iter()
1687            .rev()
1688            .find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
1689            .map_or(crate::PointerRepr::default(), |(_, repr)| repr.clone());
1690        if raw == crate::PointerRepr::Inline && !self.inlined_message_fields.contains(field_fqn) {
1691            crate::PointerRepr::Box
1692        } else {
1693            raw
1694        }
1695    }
1696
1697    /// Resolve the [`RepeatedRepr`](crate::RepeatedRepr) for a `repeated` field
1698    /// at the given proto path.
1699    ///
1700    /// `field_fqn` is the fully-qualified proto field path, e.g.
1701    /// `".my.pkg.MyMessage.items"`. Rules in `config.repeated_fields` are matched
1702    /// with the same proto-segment-aware prefix logic as
1703    /// [`string_repr`](Self::string_repr); the **last** matching rule wins,
1704    /// letting a specific override follow a broad default. Fields matching no
1705    /// rule use [`RepeatedRepr::Vec`](crate::RepeatedRepr::Vec).
1706    pub fn repeated_repr(&self, field_fqn: &str) -> crate::RepeatedRepr {
1707        self.config
1708            .repeated_fields
1709            .iter()
1710            .rev()
1711            .find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
1712            .map_or_else(
1713                || {
1714                    if field_fqn
1715                        .rsplit_once('.')
1716                        .is_some_and(|(message, _)| self.zeroizes_message(message))
1717                    {
1718                        crate::RepeatedRepr::Custom("::buffa::sensitive::List<*>".into())
1719                    } else {
1720                        crate::RepeatedRepr::default()
1721                    }
1722                },
1723                |(_, repr)| repr.clone(),
1724            )
1725    }
1726}
1727
1728/// Scope-local context for code generation within a message.
1729///
1730/// Bundles the parameters that are constant within a single message's code
1731/// generation scope and change only when recursing into nested messages.
1732/// Threading this struct instead of five individual parameters keeps function
1733/// signatures short and makes adding new scope-level state a one-field change.
1734#[derive(Clone, Copy)]
1735pub(crate) struct MessageScope<'a> {
1736    /// Global codegen context (descriptors, type map, config).
1737    pub ctx: &'a CodeGenContext<'a>,
1738    /// Proto package of the file being generated (e.g. `"google.protobuf"`).
1739    pub current_package: &'a str,
1740    /// Fully-qualified proto name of the current message
1741    /// (e.g. `"google.protobuf.Timestamp"`, `"pkg.Outer.Inner"`).
1742    pub proto_fqn: &'a str,
1743    /// Resolved edition features for this message scope.
1744    pub features: &'a ResolvedFeatures,
1745    /// Module nesting depth — number of `pub mod` levels the generated code
1746    /// sits inside.  Controls the count of `super::` prefixes in type
1747    /// references via [`CodeGenContext::rust_type_relative`].
1748    pub nesting: usize,
1749}
1750
1751impl<'a> MessageScope<'a> {
1752    /// Create a child scope for a nested message (increments nesting by 1).
1753    pub fn nested(&self, proto_fqn: &'a str, features: &'a ResolvedFeatures) -> MessageScope<'a> {
1754        MessageScope {
1755            ctx: self.ctx,
1756            current_package: self.current_package,
1757            proto_fqn,
1758            features,
1759            nesting: self.nesting + 1,
1760        }
1761    }
1762
1763    /// Whether this message stores unknown fields. See
1764    /// [`CodeGenContext::preserve_unknown_fields`].
1765    pub fn preserve_unknown_fields(&self) -> bool {
1766        self.ctx.preserve_unknown_fields(self.proto_fqn)
1767    }
1768
1769    /// Whether this message's generated JSON deserializer rejects unknown
1770    /// fields. See [`CodeGenContext::deny_unknown_json_fields`].
1771    ///
1772    /// Gated on [`CodeGenConfig::generate_json`](crate::CodeGenConfig::generate_json):
1773    /// with JSON off there is no deserializer to make strict, so every
1774    /// emission site asking through here agrees without repeating the check.
1775    pub fn deny_unknown_json_fields(&self) -> bool {
1776        self.ctx.config.generate_json && self.ctx.deny_unknown_json_fields(self.proto_fqn)
1777    }
1778}
1779
1780/// Kind of ancillary tree under the [`SENTINEL_MOD`] module.
1781///
1782/// `path_segments()` returns the module path *inside* `__buffa::` (not
1783/// including the sentinel itself).
1784#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1785pub(crate) enum AncillaryKind {
1786    /// `__buffa::oneof::<msg_path>::` — owned oneof enums.
1787    Oneof,
1788    /// `__buffa::view::<msg_path>::` — message view structs.
1789    View,
1790    /// `__buffa::view::oneof::<msg_path>::` — view oneof enums.
1791    ViewOneof,
1792    /// `__buffa::lazy_view::<msg_path>::` — lazy view structs.
1793    LazyView,
1794}
1795
1796impl AncillaryKind {
1797    fn path_segments(self) -> &'static [&'static str] {
1798        match self {
1799            Self::Oneof => &["oneof"],
1800            Self::View => &["view"],
1801            Self::ViewOneof => &["view", "oneof"],
1802            Self::LazyView => &["lazy_view"],
1803        }
1804    }
1805}
1806
1807/// Build a token-stream path prefix from an emission scope to an ancillary
1808/// kind's location for the **current** message (`proto_fqn`).
1809///
1810/// Always climbs to the package root via `super::` and re-descends through
1811/// `__buffa::<kind>::<msg_path>::` — uniform regardless of where the caller
1812/// sits. `<msg_path>` is the nested-types module of each enclosing message,
1813/// then of the message itself, as [`CodeGenContext::message_module_name`]
1814/// returns them. `from_nesting` is the caller's total module depth below the
1815/// package root (message-nesting plus any `__buffa::<kind>::` levels the
1816/// caller is already inside).
1817///
1818/// `proto_fqn` follows the dotless convention used throughout codegen
1819/// (e.g. `"google.protobuf.Value"`, not `".google.protobuf.Value"`).
1820///
1821/// Returned tokens always end with `::` so callers append the type
1822/// identifier directly: `quote! { #prefix #ident }`.
1823pub(crate) fn ancillary_prefix(
1824    ctx: &CodeGenContext<'_>,
1825    kind: AncillaryKind,
1826    current_package: &str,
1827    proto_fqn: &str,
1828    from_nesting: usize,
1829) -> proc_macro2::TokenStream {
1830    use crate::idents::make_field_ident;
1831    use quote::quote;
1832
1833    debug_assert!(
1834        !proto_fqn.starts_with('.'),
1835        "ancillary_prefix expects dotless FQN, got {proto_fqn:?}"
1836    );
1837
1838    let mut supers_tokens = proc_macro2::TokenStream::new();
1839    for _ in 0..from_nesting {
1840        supers_tokens.extend(quote! { super:: });
1841    }
1842
1843    let sentinel = make_field_ident(SENTINEL_MOD);
1844    let kind_segs: Vec<_> = kind
1845        .path_segments()
1846        .iter()
1847        .map(|s| make_field_ident(s))
1848        .collect();
1849
1850    // Module path of the message within the package (e.g. "outer::inner::"):
1851    // the nested-types module of each enclosing message, then its own.
1852    let within_pkg = if current_package.is_empty() {
1853        proto_fqn
1854    } else {
1855        proto_fqn
1856            .strip_prefix(current_package)
1857            .and_then(|s| s.strip_prefix('.'))
1858            .unwrap_or(proto_fqn)
1859    };
1860    let mut fqn = current_package.to_string();
1861    let mut msg_segs = Vec::new();
1862    for name in within_pkg.split('.').filter(|s| !s.is_empty()) {
1863        if !fqn.is_empty() {
1864            fqn.push('.');
1865        }
1866        fqn.push_str(name);
1867        msg_segs.push(make_field_ident(&ctx.message_module_name(&fqn)));
1868    }
1869
1870    quote! { #supers_tokens #sentinel :: #(#kind_segs ::)* #(#msg_segs ::)* }
1871}
1872
1873/// Proto-segment-aware prefix match: `prefix` matches `fqn_dotted` if
1874/// `prefix == "."`, the two are equal, or `fqn_dotted` starts with `prefix`
1875/// followed by a `.` boundary. Proto identifiers are ASCII, and `.` is ASCII,
1876/// so byte indexing is safe.
1877pub(crate) fn matches_proto_prefix(prefix: &str, fqn_dotted: &str) -> bool {
1878    prefix == "."
1879        || prefix == fqn_dotted
1880        || (fqn_dotted.starts_with(prefix)
1881            && fqn_dotted.as_bytes().get(prefix.len()) == Some(&b'.'))
1882}
1883
1884/// Look up a file-level extern mapping by exact proto file path.
1885///
1886/// Unlike [`resolve_extern_prefix`], this does no prefix or package
1887/// arithmetic — file-level mappings are auto-injected for a known closed set
1888/// of bootstrap protos (`descriptor.proto`, `compiler/plugin.proto`) whose
1889/// types live in a different crate (`buffa-descriptor`) than the rest of the
1890/// `google.protobuf` package (`buffa-types`). The mapped Rust module is the
1891/// root of that file's generated module, with no further suffix.
1892fn resolve_file_extern<'p>(
1893    file_name: &str,
1894    file_extern_paths: &'p [(String, String)],
1895) -> Option<&'p str> {
1896    file_extern_paths
1897        .iter()
1898        .find(|(name, _)| name == file_name)
1899        .map(|(_, rust)| rust.as_str())
1900}
1901
1902/// Check if a proto package matches any extern_path prefix.
1903///
1904/// Returns the Rust module path root if matched, including any remaining
1905/// package segments converted to `snake_case` modules. For example,
1906/// extern_path `(".my", "::my_crate")` with package `"my.sub.pkg"` returns
1907/// `"::my_crate::sub::pkg"`.
1908///
1909/// `pub(crate)`: also called from `crate::effective_file_extern_paths` to
1910/// suppress an auto-injected file-level mapping when a user package-level
1911/// extern_path already covers that file's package.
1912pub(crate) fn resolve_extern_prefix(
1913    package: &str,
1914    extern_paths: &[(String, String)],
1915) -> Option<String> {
1916    let dotted = format!(".{}", package);
1917
1918    // Try longest prefix first so that more specific mappings take priority
1919    // over broader ones (e.g., ".my.common" before ".my").
1920    let mut best: Option<(&str, &str, usize)> = None;
1921
1922    for (proto_prefix, rust_prefix) in extern_paths {
1923        if dotted == *proto_prefix {
1924            // Exact match is always the best.
1925            return Some(rust_prefix.clone());
1926        }
1927        if let Some(rest) = dotted.strip_prefix(proto_prefix.as_str()) {
1928            // `"."` is the catch-all root; stripping it leaves no leading dot.
1929            if proto_prefix == "." || rest.starts_with('.') {
1930                let prefix_len = proto_prefix.len();
1931                // MSRV: `Option::is_none_or` requires 1.82.
1932                if best.map_or(true, |(_, _, best_len)| prefix_len > best_len) {
1933                    best = Some((proto_prefix, rust_prefix, prefix_len));
1934                }
1935            }
1936        }
1937    }
1938
1939    let (proto_prefix, rust_prefix, _) = best?;
1940    let rest = dotted.strip_prefix(proto_prefix)?;
1941    let rest = rest.strip_prefix('.').unwrap_or(rest);
1942    let suffix = rest
1943        .split('.')
1944        .map(to_snake_case)
1945        .collect::<Vec<_>>()
1946        .join("::");
1947    Some(format!("{}::{}", rust_prefix, suffix))
1948}
1949
1950/// Resolve a fully-qualified proto **type** name against `extern_paths`,
1951/// mirroring prost's `resolve_ident` (issue #111).
1952///
1953/// Unlike [`resolve_extern_prefix`] — which only matches a file's *package* and
1954/// returns the package's Rust module — this matches the type's whole FQN:
1955///
1956/// 1. An **exact** `extern_path` entry for the FQN wins (a per-type override,
1957///    e.g. `.google.protobuf.Timestamp = ::pbjson_types::Timestamp`).
1958/// 2. Otherwise the **longest dotted-prefix** entry (a package or an enclosing
1959///    type) applies, with the proto segments past that prefix rendered as
1960///    `snake_case` modules and the final segment as the Rust type name, escaped
1961///    by [`escape_type_name`](crate::idents::escape_type_name) —
1962///    exactly the path [`CodeGenContext::new`] would otherwise build from
1963///    [`resolve_extern_prefix`] plus the type name, so package-prefix mappings
1964///    resolve identically to before.
1965///
1966/// `fqn` is the leading-dot form (e.g. `.google.protobuf.Timestamp`). Returns
1967/// the full Rust type path, or `None` when nothing matches (the caller falls
1968/// back to the local package path).
1969pub(crate) fn resolve_extern_type(fqn: &str, extern_paths: &[(String, String)]) -> Option<String> {
1970    // 1. Exact per-type entry — the mapping *is* the full Rust path.
1971    if let Some((_, rust)) = extern_paths.iter().find(|(proto, _)| proto == fqn) {
1972        return Some(rust.clone());
1973    }
1974
1975    // 2. Longest dotted-prefix entry (package or enclosing type).
1976    let mut best: Option<(&str, &str, usize)> = None;
1977    for (proto_prefix, rust_prefix) in extern_paths {
1978        let matches = proto_prefix == "."
1979            || fqn
1980                .strip_prefix(proto_prefix.as_str())
1981                .is_some_and(|rest| rest.starts_with('.'));
1982        // MSRV: `Option::is_none_or` requires 1.82.
1983        if matches && best.map_or(true, |(_, _, best_len)| proto_prefix.len() > best_len) {
1984            best = Some((proto_prefix, rust_prefix, proto_prefix.len()));
1985        }
1986    }
1987
1988    let (proto_prefix, rust_prefix, _) = best?;
1989    // The catch-all `.` leaves the whole FQN (minus its leading dot); any other
1990    // prefix leaves the `.`-separated remainder after the matched boundary.
1991    let rest = if proto_prefix == "." {
1992        fqn.strip_prefix('.').unwrap_or(fqn)
1993    } else {
1994        fqn.strip_prefix(proto_prefix)
1995            .and_then(|r| r.strip_prefix('.'))
1996            .unwrap_or("")
1997    };
1998    let mut segments = rest.split('.').collect::<Vec<_>>();
1999    // The final segment is the type name, escaped by the rule the owning
2000    // crate's codegen applied; the rest are modules.
2001    let type_name = segments.pop()?;
2002    let mut path = rust_prefix.to_string();
2003    for module in segments {
2004        path.push_str("::");
2005        path.push_str(&to_snake_case(module));
2006    }
2007    path.push_str("::");
2008    path.push_str(&crate::idents::escape_type_name(type_name));
2009    Some(path)
2010}
2011
2012/// Join a Rust module path and a type name, handling the empty (no-package)
2013/// module by returning the bare type name.
2014fn join_mod(module: &str, name: &str) -> String {
2015    if module.is_empty() {
2016        name.to_string()
2017    } else {
2018        format!("{module}::{name}")
2019    }
2020}
2021
2022/// Resolve a registered type's Rust path, applying per-type `extern_path`
2023/// overrides (issue #111).
2024///
2025/// Priority, most specific first: an **exact** per-type FQN entry, then a
2026/// **file-level** mapping (the internal `descriptor.proto` → `buffa-descriptor`
2027/// split, which must outrank a package prefix), then the **longest
2028/// dotted-prefix** entry (package or enclosing type, via [`resolve_extern_type`]),
2029/// then the **local** package path.
2030///
2031/// Returns `(rust_path, is_extern)`; `is_extern` is `false` only for the local
2032/// fallback, telling the caller whether the type emits a local module.
2033fn resolve_type_path(
2034    fqn: &str,
2035    name: &str,
2036    file_root: Option<&str>,
2037    local_module: &str,
2038    extern_paths: &[(String, String)],
2039    type_name_prefix: &str,
2040) -> (String, bool) {
2041    // The exact check is done here (not left to `resolve_extern_type`) so an
2042    // exact per-type entry outranks the file-level mapping below; once it has
2043    // failed, `resolve_extern_type`'s own exact pass can only fall through to
2044    // its prefix logic.
2045    //
2046    // `type_name_prefix` applies only to the local fallback: extern-mapped
2047    // types are named by the external crate, and the file-level root is the
2048    // internal descriptor.proto → buffa-descriptor split (also external to
2049    // this codegen run).
2050    if let Some((_, rust)) = extern_paths.iter().find(|(proto, _)| proto == fqn) {
2051        (rust.clone(), true)
2052    } else if let Some(root) = file_root {
2053        (join_mod(root, name), true)
2054    } else if let Some(path) = resolve_extern_type(fqn, extern_paths) {
2055        (path, true)
2056    } else {
2057        (
2058            join_mod(
2059                local_module,
2060                &crate::idents::local_type_name(type_name_prefix, name),
2061            ),
2062            false,
2063        )
2064    }
2065}
2066
2067/// Per-file invariants of [`register_nested_types`], bundled so the
2068/// recursion only threads the parent FQN / module that actually vary.
2069#[derive(Clone, Copy)]
2070struct NestedRegistrationCtx<'a> {
2071    package: &'a str,
2072    extern_paths: &'a [(String, String)],
2073    type_name_prefix: &'a str,
2074}
2075
2076/// Recursively register nested messages and enums with module-qualified paths.
2077///
2078/// Each nested message `Parent.Child` maps to `parent_mod::Child` in Rust,
2079/// where `parent_mod` is the module path of the enclosing message's nested
2080/// types. A nested message whose own module is not named `snake_case(Child)`
2081/// (see [`deconflict_modules`]) is recorded in `module_names`.
2082///
2083/// A per-type `extern_path` override (issue #111) on a nested type's own FQN
2084/// takes priority over the inherited `parent_mod` path; otherwise the nested
2085/// type simply lives in `parent_mod` — which already reflects any override of an
2086/// enclosing type, so a parent override cascades to its descendants.
2087fn register_nested_types(
2088    type_map: &mut HashMap<String, String>,
2089    package_of: &mut HashMap<String, String>,
2090    module_names: &mut HashMap<String, String>,
2091    reg: NestedRegistrationCtx<'_>,
2092    parent_fqn: &str,
2093    parent_mod: &str,
2094    msg: &crate::generated::descriptor::DescriptorProto,
2095) {
2096    let NestedRegistrationCtx {
2097        package,
2098        extern_paths,
2099        type_name_prefix,
2100    } = reg;
2101    let extern_override = |fqn: &str| {
2102        extern_paths
2103            .iter()
2104            .find(|(proto, _)| proto == fqn)
2105            .map(|(_, rust)| rust.as_str())
2106    };
2107
2108    // The module of each nested message that is declared in `parent_mod`,
2109    // by proto name. A module cannot take the name of a type declared beside
2110    // it. A map entry declares neither a type nor a module.
2111    let is_local = |name: &&String| extern_override(&format!("{parent_fqn}.{name}")).is_none();
2112    let is_map_entry = |nested: &&crate::generated::descriptor::DescriptorProto| {
2113        nested
2114            .options
2115            .as_option()
2116            .and_then(|o| o.map_entry)
2117            .unwrap_or(false)
2118    };
2119    let local: Vec<String> = msg
2120        .nested_type
2121        .iter()
2122        .filter(|nested| !is_map_entry(nested))
2123        .filter_map(|nested| nested.name.as_ref())
2124        .filter(is_local)
2125        .cloned()
2126        .collect();
2127    let local_modules: HashMap<&str, String> = if local.is_empty() {
2128        HashMap::new()
2129    } else {
2130        let enums = msg.enum_type.iter().filter_map(|e| e.name.as_ref());
2131        let occupied: HashSet<String> = local
2132            .iter()
2133            .chain(enums.filter(is_local))
2134            .map(|name| crate::idents::local_type_name(type_name_prefix, name))
2135            .collect();
2136        let modules = deconflict_modules(&local, &occupied);
2137        local.iter().map(String::as_str).zip(modules).collect()
2138    };
2139
2140    for nested in &msg.nested_type {
2141        if let Some(name) = &nested.name {
2142            let fqn = format!("{}.{}", parent_fqn, name);
2143            // An exact per-type override wins; the child module is then
2144            // beside the override's type. Otherwise the type is in
2145            // `parent_mod`, named with the configured prefix, and its own
2146            // nested types are in the module chosen above.
2147            let (rust_path, child_mod) = match extern_override(&fqn) {
2148                Some(rust) => {
2149                    let module = extern_override_module(name, rust, false);
2150                    let child = match rust.rsplit_once("::") {
2151                        Some((parent, _)) => format!("{parent}::{module}"),
2152                        None => module,
2153                    };
2154                    (rust.to_string(), child)
2155                }
2156                None => {
2157                    let module = local_modules
2158                        .get(name.as_str())
2159                        .cloned()
2160                        .unwrap_or_else(|| to_snake_case(name));
2161                    if module != to_snake_case(name) {
2162                        module_names.insert(fqn.clone(), module.clone());
2163                    }
2164                    (
2165                        format!(
2166                            "{parent_mod}::{}",
2167                            crate::idents::local_type_name(type_name_prefix, name)
2168                        ),
2169                        format!("{parent_mod}::{module}"),
2170                    )
2171                }
2172            };
2173            type_map.insert(fqn.clone(), rust_path);
2174            package_of.insert(fqn.clone(), package.to_string());
2175
2176            // Recurse: nested-of-nested goes in a deeper module.
2177            register_nested_types(
2178                type_map,
2179                package_of,
2180                module_names,
2181                reg,
2182                &fqn,
2183                &child_mod,
2184                nested,
2185            );
2186        }
2187    }
2188
2189    for enum_type in &msg.enum_type {
2190        if let Some(name) = &enum_type.name {
2191            let fqn = format!("{}.{}", parent_fqn, name);
2192            let rust_path = extern_override(&fqn).map_or_else(
2193                || {
2194                    format!(
2195                        "{parent_mod}::{}",
2196                        crate::idents::local_type_name(type_name_prefix, name)
2197                    )
2198                },
2199                str::to_string,
2200            );
2201            type_map.insert(fqn.clone(), rust_path);
2202            package_of.insert(fqn, package.to_string());
2203        }
2204    }
2205}
2206
2207/// Record every enum's first declared value number, keyed by dotted FQN
2208/// (same key form as `enum_closedness`).
2209fn collect_enum_first_values(files: &[FileDescriptorProto]) -> HashMap<String, i32> {
2210    fn record(map: &mut HashMap<String, i32>, prefix: &str, e: &EnumDescriptorProto) {
2211        if let (Some(name), Some(first)) = (e.name.as_deref(), e.value.first()) {
2212            map.insert(format!("{prefix}{name}"), first.number.unwrap_or(0));
2213        }
2214    }
2215    fn walk_msg(map: &mut HashMap<String, i32>, prefix: &str, msg: &DescriptorProto) {
2216        let Some(name) = msg.name.as_deref() else {
2217            return;
2218        };
2219        let child_prefix = format!("{prefix}{name}.");
2220        for e in &msg.enum_type {
2221            record(map, &child_prefix, e);
2222        }
2223        for nested in &msg.nested_type {
2224            walk_msg(map, &child_prefix, nested);
2225        }
2226    }
2227
2228    let mut map = HashMap::new();
2229    for file in files {
2230        let prefix = match file.package.as_deref() {
2231            Some(p) if !p.is_empty() => format!(".{p}."),
2232            _ => ".".to_string(),
2233        };
2234        for e in &file.enum_type {
2235            record(&mut map, &prefix, e);
2236        }
2237        for msg in &file.message_type {
2238            walk_msg(&mut map, &prefix, msg);
2239        }
2240    }
2241    map
2242}
2243
2244/// The proto names of each enum's values whose generated item is
2245/// `#[deprecated]`, keyed by dotted FQN (same key form as
2246/// [`collect_enum_first_values`]). Consulted only to decide whether a
2247/// generated item that spells out an enum value — a `[default = V]`
2248/// expression — needs `#[allow(deprecated)]`.
2249fn collect_deprecated_enum_values(
2250    files: &[FileDescriptorProto],
2251) -> HashMap<String, HashSet<String>> {
2252    fn record(map: &mut HashMap<String, HashSet<String>>, prefix: &str, e: &EnumDescriptorProto) {
2253        let Some(name) = e.name.as_deref() else {
2254            return;
2255        };
2256        let fqn = format!("{prefix}{name}");
2257        let deprecated = crate::enumeration::deprecated_items(e);
2258        for (v, _) in e.value.iter().zip(deprecated).filter(|(_, d)| *d) {
2259            if let Some(value_name) = v.name.as_deref() {
2260                map.entry(fqn.clone())
2261                    .or_default()
2262                    .insert(value_name.to_string());
2263            }
2264        }
2265    }
2266    fn walk_msg(map: &mut HashMap<String, HashSet<String>>, prefix: &str, msg: &DescriptorProto) {
2267        let Some(name) = msg.name.as_deref() else {
2268            return;
2269        };
2270        let child_prefix = format!("{prefix}{name}.");
2271        for e in &msg.enum_type {
2272            record(map, &child_prefix, e);
2273        }
2274        for nested in &msg.nested_type {
2275            walk_msg(map, &child_prefix, nested);
2276        }
2277    }
2278
2279    let mut map = HashMap::new();
2280    for file in files {
2281        let prefix = match file.package.as_deref() {
2282            Some(p) if !p.is_empty() => format!(".{p}."),
2283            _ => ".".to_string(),
2284        };
2285        for e in &file.enum_type {
2286            record(&mut map, &prefix, e);
2287        }
2288        for msg in &file.message_type {
2289            walk_msg(&mut map, &prefix, msg);
2290        }
2291    }
2292    map
2293}
2294
2295/// Resolve and record whether an enum is closed, given its parent's features.
2296fn register_enum_closedness(
2297    map: &mut HashMap<String, bool>,
2298    fqn: &str,
2299    parent_features: &ResolvedFeatures,
2300    enum_desc: &EnumDescriptorProto,
2301) {
2302    let resolved = features::resolve_child(parent_features, features::enum_features(enum_desc));
2303    let closed = resolved.enum_type == features::EnumType::Closed;
2304    map.insert(fqn.to_string(), closed);
2305}
2306
2307/// Walk nested messages and register all enum closedness, resolving features
2308/// through the message hierarchy (file → msg → nested_msg → enum).
2309fn register_nested_enum_closedness(
2310    map: &mut HashMap<String, bool>,
2311    parent_fqn: &str,
2312    parent_features: &ResolvedFeatures,
2313    msg: &DescriptorProto,
2314) {
2315    let msg_features = features::resolve_child(parent_features, features::message_features(msg));
2316    for enum_type in &msg.enum_type {
2317        if let Some(name) = &enum_type.name {
2318            let fqn = format!("{}.{}", parent_fqn, name);
2319            register_enum_closedness(map, &fqn, &msg_features, enum_type);
2320        }
2321    }
2322    for nested in &msg.nested_type {
2323        if let Some(name) = &nested.name {
2324            let fqn = format!("{}.{}", parent_fqn, name);
2325            register_nested_enum_closedness(map, &fqn, &msg_features, nested);
2326        }
2327    }
2328}
2329
2330/// A whitespace-insensitive key for a Rust type path, for comparing the paths
2331/// in [`json_policy_types`](CodeGenConfig::json_policy_types) with those in
2332/// representation rules. A path that does not parse is compared verbatim; its
2333/// representation rule reports the parse error.
2334pub(crate) fn rust_type_key(path: &str) -> String {
2335    match syn::parse_str::<syn::Type>(path) {
2336        Ok(ty) => quote::ToTokens::to_token_stream(&ty).to_string(),
2337        Err(_) => path.to_owned(),
2338    }
2339}
2340
2341/// Final path segment used to detect a policy-list spelling mismatch.
2342pub(crate) fn rust_type_name(path: &str) -> Option<String> {
2343    match syn::parse_str::<syn::Type>(path).ok()? {
2344        syn::Type::Path(path) => path
2345            .path
2346            .segments
2347            .last()
2348            .map(|segment| segment.ident.to_string()),
2349        _ => None,
2350    }
2351}
2352
2353#[cfg(test)]
2354mod tests {
2355    use super::*;
2356    use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
2357
2358    fn set(names: &[&str]) -> HashSet<String> {
2359        names.iter().map(|s| s.to_string()).collect()
2360    }
2361
2362    fn names(ns: &[&str]) -> Vec<String> {
2363        ns.iter().map(|s| s.to_string()).collect()
2364    }
2365
2366    #[test]
2367    fn deconflict_no_collision_keeps_base() {
2368        // No sub-package shares a module name → names are unchanged.
2369        let out = deconflict_modules(&names(&["Oof", "Bar"]), &set(&["other"]));
2370        assert_eq!(out, vec!["oof".to_string(), "bar".to_string()]);
2371    }
2372
2373    #[test]
2374    fn deconflict_single_collision_appends_underscore() {
2375        let out = deconflict_modules(&names(&["Oof"]), &set(&["oof"]));
2376        assert_eq!(out, vec!["oof_".to_string()]);
2377    }
2378
2379    #[test]
2380    fn deconflict_repeated_append_when_underscore_slot_also_taken() {
2381        // Sub-packages `oof` AND `oof_` both exist → grow past both.
2382        let out = deconflict_modules(&names(&["Oof"]), &set(&["oof", "oof_"]));
2383        assert_eq!(out, vec!["oof__".to_string()]);
2384    }
2385
2386    #[test]
2387    fn deconflict_two_messages_racing_to_same_slot_stay_distinct() {
2388        // `Oof` (oof) and `Oof_` (oof_), sub-packages `oof` and `oof_`. Without
2389        // the shared `taken` set both would land on `oof__`.
2390        let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof", "oof_"]));
2391        assert_eq!(out, vec!["oof__".to_string(), "oof___".to_string()]);
2392        // All distinct and clear of the sub-package modules.
2393        let set: HashSet<&String> = out.iter().collect();
2394        assert_eq!(set.len(), out.len());
2395        assert!(!out.contains(&"oof".to_string()) && !out.contains(&"oof_".to_string()));
2396    }
2397
2398    #[test]
2399    fn deconflict_is_independent_of_declaration_order() {
2400        // Reordering the input must not change which message gets which name.
2401        let ch = set(&["oof", "oof_"]);
2402        let fwd = deconflict_modules(&names(&["Oof", "Oof_"]), &ch);
2403        let rev = deconflict_modules(&names(&["Oof_", "Oof"]), &ch);
2404        // fwd: [Oof, Oof_]; rev: [Oof_, Oof] — same per-name mapping either way.
2405        assert_eq!(fwd, vec!["oof__".to_string(), "oof___".to_string()]);
2406        assert_eq!(rev, vec!["oof___".to_string(), "oof__".to_string()]);
2407    }
2408
2409    #[test]
2410    fn deconflict_avoids_other_messages_raw_base() {
2411        // `Oof` collides with sub-package `oof`; its `oof_` candidate must also
2412        // avoid the raw module of a sibling message `Oof_`.
2413        let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof"]));
2414        // Oof -> oof_ is taken by Oof_'s raw base, so Oof -> oof__; Oof_ stays.
2415        assert_eq!(out, vec!["oof__".to_string(), "oof_".to_string()]);
2416    }
2417
2418    #[test]
2419    fn deconflict_avoids_type_names_and_reserved_names() {
2420        // `message item` declares `struct item`. `crate` cannot name a module,
2421        // and `arbitrary` is reserved whatever the config.
2422        let out = deconflict_modules(
2423            &names(&["item", "Crate", "Arbitrary", "Other"]),
2424            &set(&["item"]),
2425        );
2426        assert_eq!(out, ["item_", "crate_", "arbitrary_", "other"]);
2427    }
2428
2429    #[test]
2430    fn deconflict_suffix_skips_a_type_of_that_name() {
2431        // `message crate` is the struct `crate_`, so its module is `crate__`.
2432        let out = deconflict_modules(&names(&["crate"]), &set(&["crate_"]));
2433        assert_eq!(out, ["crate__"]);
2434    }
2435
2436    #[test]
2437    fn deconflict_order_of_equal_bases_follows_the_proto_name() {
2438        // `Item` and `item` in two files of one package both have the base
2439        // `item`, which `struct item` takes.
2440        let occupied = set(&["Item", "item"]);
2441        assert_eq!(
2442            deconflict_modules(&names(&["Item", "item"]), &occupied),
2443            ["item_", "item__"]
2444        );
2445        assert_eq!(
2446            deconflict_modules(&names(&["item", "Item"]), &occupied),
2447            ["item__", "item_"]
2448        );
2449    }
2450
2451    #[test]
2452    fn extern_override_module_follows_the_mapped_type_name() {
2453        let module = |name, path| extern_override_module(name, path, false);
2454        assert_eq!(module("Outer", "::ext::Outer"), "outer");
2455        assert_eq!(module("item", "::ext::item"), "item_");
2456        // The owning crate used a `type_name_prefix`, so `item` is free there.
2457        assert_eq!(module("item", "::ext::Pbitem"), "item");
2458        assert_eq!(module("Crate", "::ext::Crate"), "crate_");
2459        assert_eq!(module("crate", "::ext::crate_"), "crate__");
2460        // `oneof` is taken at package level only.
2461        assert_eq!(module("Oneof", "::ext::outer::Oneof"), "oneof");
2462        assert_eq!(
2463            extern_override_module("Oneof", "::ext::Oneof", true),
2464            "oneof_"
2465        );
2466    }
2467
2468    #[test]
2469    fn deconflict_never_yields_the_sentinel() {
2470        let out = deconflict_modules(&names(&["Buffa"]), &set(&["__buffa", "buffa"]));
2471        // base `buffa` collides; `buffa_` is free, so it is chosen (not __buffa).
2472        assert_eq!(out, vec!["buffa_".to_string()]);
2473        assert_ne!(out[0], SENTINEL_MOD);
2474    }
2475
2476    #[test]
2477    fn child_package_segments_extracts_immediate_segment() {
2478        let pkgs = set(&["foo", "foo.oof", "foo.bar.baz", "foobar"]);
2479        let mut got: Vec<String> = child_package_segments("foo", &pkgs).into_iter().collect();
2480        got.sort();
2481        // `foo.oof` -> oof, `foo.bar.baz` -> bar; `foobar` is not a sub-package.
2482        assert_eq!(got, vec!["bar".to_string(), "oof".to_string()]);
2483    }
2484
2485    fn make_file(
2486        name: &str,
2487        package: &str,
2488        messages: Vec<DescriptorProto>,
2489        enums: Vec<EnumDescriptorProto>,
2490    ) -> FileDescriptorProto {
2491        FileDescriptorProto {
2492            name: Some(name.to_string()),
2493            package: if package.is_empty() {
2494                None
2495            } else {
2496                Some(package.to_string())
2497            },
2498            message_type: messages,
2499            enum_type: enums,
2500            ..Default::default()
2501        }
2502    }
2503
2504    fn msg(name: &str) -> DescriptorProto {
2505        DescriptorProto {
2506            name: Some(name.to_string()),
2507            ..Default::default()
2508        }
2509    }
2510
2511    fn msg_with_nested(name: &str, nested: Vec<DescriptorProto>) -> DescriptorProto {
2512        DescriptorProto {
2513            name: Some(name.to_string()),
2514            nested_type: nested,
2515            ..Default::default()
2516        }
2517    }
2518
2519    fn msg_with_nested_and_enums(
2520        name: &str,
2521        nested: Vec<DescriptorProto>,
2522        enums: Vec<EnumDescriptorProto>,
2523    ) -> DescriptorProto {
2524        DescriptorProto {
2525            name: Some(name.to_string()),
2526            nested_type: nested,
2527            enum_type: enums,
2528            ..Default::default()
2529        }
2530    }
2531
2532    fn enum_desc(name: &str) -> EnumDescriptorProto {
2533        EnumDescriptorProto {
2534            name: Some(name.to_string()),
2535            ..Default::default()
2536        }
2537    }
2538
2539    fn enum_with_closed_feature(name: &str) -> EnumDescriptorProto {
2540        use crate::generated::descriptor::{feature_set, EnumOptions, FeatureSet};
2541        EnumDescriptorProto {
2542            name: Some(name.to_string()),
2543            options: buffa::MessageField::some(EnumOptions {
2544                features: buffa::MessageField::some(FeatureSet {
2545                    enum_type: Some(feature_set::EnumType::CLOSED),
2546                    ..Default::default()
2547                }),
2548                ..Default::default()
2549            }),
2550            ..Default::default()
2551        }
2552    }
2553
2554    fn editions_file(
2555        name: &str,
2556        package: &str,
2557        messages: Vec<DescriptorProto>,
2558        enums: Vec<EnumDescriptorProto>,
2559    ) -> FileDescriptorProto {
2560        use crate::generated::descriptor::Edition;
2561        FileDescriptorProto {
2562            name: Some(name.to_string()),
2563            package: Some(package.to_string()),
2564            syntax: Some("editions".to_string()),
2565            edition: Some(Edition::EDITION_2023),
2566            message_type: messages,
2567            enum_type: enums,
2568            ..Default::default()
2569        }
2570    }
2571
2572    // ── Type registration tests ──────────────────────────────────────────
2573
2574    #[test]
2575    fn test_message_with_package() {
2576        let files = [make_file(
2577            "test.proto",
2578            "my.package",
2579            vec![msg("Foo")],
2580            vec![],
2581        )];
2582        let config = CodeGenConfig::default();
2583        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2584        assert_eq!(ctx.rust_type(".my.package.Foo"), Some("my::package::Foo"));
2585    }
2586
2587    #[test]
2588    fn test_message_no_package() {
2589        let files = [make_file("test.proto", "", vec![msg("Bar")], vec![])];
2590        let config = CodeGenConfig::default();
2591        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2592        assert_eq!(ctx.rust_type(".Bar"), Some("Bar"));
2593    }
2594
2595    #[test]
2596    fn test_nested_message_uses_module_path() {
2597        let outer = msg_with_nested("Outer", vec![msg("Inner")]);
2598        let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
2599        let config = CodeGenConfig::default();
2600        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2601        assert_eq!(ctx.rust_type(".pkg.Outer"), Some("pkg::Outer"));
2602        // Nested types use module-qualified paths.
2603        assert_eq!(ctx.rust_type(".pkg.Outer.Inner"), Some("pkg::outer::Inner"));
2604    }
2605
2606    #[test]
2607    fn test_nested_message_no_package() {
2608        let outer = msg_with_nested("Outer", vec![msg("Inner")]);
2609        let files = [make_file("test.proto", "", vec![outer], vec![])];
2610        let config = CodeGenConfig::default();
2611        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2612        assert_eq!(ctx.rust_type(".Outer"), Some("Outer"));
2613        assert_eq!(ctx.rust_type(".Outer.Inner"), Some("outer::Inner"));
2614    }
2615
2616    #[test]
2617    fn test_deeply_nested_message() {
2618        let deep = msg_with_nested("A", vec![msg_with_nested("B", vec![msg("C")])]);
2619        let files = [make_file("test.proto", "pkg", vec![deep], vec![])];
2620        let config = CodeGenConfig::default();
2621        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2622        assert_eq!(ctx.rust_type(".pkg.A"), Some("pkg::A"));
2623        assert_eq!(ctx.rust_type(".pkg.A.B"), Some("pkg::a::B"));
2624        assert_eq!(ctx.rust_type(".pkg.A.B.C"), Some("pkg::a::b::C"));
2625    }
2626
2627    #[test]
2628    fn test_nested_enum_uses_module_path() {
2629        let outer = msg_with_nested_and_enums("Outer", vec![], vec![enum_desc("Status")]);
2630        let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
2631        let config = CodeGenConfig::default();
2632        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2633        assert_eq!(
2634            ctx.rust_type(".pkg.Outer.Status"),
2635            Some("pkg::outer::Status")
2636        );
2637    }
2638
2639    #[test]
2640    fn test_top_level_enum() {
2641        let files = [make_file(
2642            "test.proto",
2643            "pkg",
2644            vec![],
2645            vec![enum_desc("Status")],
2646        )];
2647        let config = CodeGenConfig::default();
2648        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2649        assert_eq!(ctx.rust_type(".pkg.Status"), Some("pkg::Status"));
2650    }
2651
2652    #[test]
2653    fn test_same_named_nested_types_in_different_parents_are_distinct() {
2654        let outer1 = msg_with_nested("Outer1", vec![msg("Inner")]);
2655        let outer2 = msg_with_nested("Outer2", vec![msg("Inner")]);
2656        let files = [make_file("a.proto", "pkg", vec![outer1, outer2], vec![])];
2657        let config = CodeGenConfig::default();
2658        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2659        // Different parent modules make them distinct.
2660        assert_eq!(
2661            ctx.rust_type(".pkg.Outer1.Inner"),
2662            Some("pkg::outer1::Inner")
2663        );
2664        assert_eq!(
2665            ctx.rust_type(".pkg.Outer2.Inner"),
2666            Some("pkg::outer2::Inner")
2667        );
2668        assert_ne!(
2669            ctx.rust_type(".pkg.Outer1.Inner"),
2670            ctx.rust_type(".pkg.Outer2.Inner")
2671        );
2672    }
2673
2674    #[test]
2675    fn test_multiple_files() {
2676        let files = [
2677            make_file("a.proto", "ns.a", vec![msg("MsgA")], vec![]),
2678            make_file("b.proto", "ns.b", vec![msg("MsgB")], vec![]),
2679        ];
2680        let config = CodeGenConfig::default();
2681        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2682        assert_eq!(ctx.rust_type(".ns.a.MsgA"), Some("ns::a::MsgA"));
2683        assert_eq!(ctx.rust_type(".ns.b.MsgB"), Some("ns::b::MsgB"));
2684    }
2685
2686    // ── Per-type FQN extern_path resolution (issue #111) ──────────────────
2687    //
2688    // `extern_path` historically matched only at the package-prefix level, so
2689    // a mapping naming a concrete type FQN (e.g.
2690    // `.google.protobuf.Timestamp=::pbjson_types::Timestamp`, a normal
2691    // prost/tonic idiom) was silently ignored. These tests pin the prost
2692    // `resolve_ident` behavior: an exact type FQN entry wins, otherwise the
2693    // longest dotted-prefix (package or enclosing type) applies.
2694
2695    #[test]
2696    fn test_extern_path_exact_per_type_match() {
2697        let files = [make_file(
2698            "test.proto",
2699            "test.pkg",
2700            vec![msg("Msg")],
2701            vec![],
2702        )];
2703        let config = CodeGenConfig {
2704            extern_paths: vec![(".test.pkg.Msg".into(), "::ext_crate::Msg".into())],
2705            ..Default::default()
2706        };
2707        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2708        // An exact per-type FQN mapping must be honored, not silently dropped.
2709        assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
2710    }
2711
2712    #[test]
2713    fn test_extern_path_per_type_overrides_package_prefix() {
2714        // Package-level mapping covers the whole package; an exact per-type
2715        // entry overrides it for that one type (exact-match-first), while a
2716        // sibling still resolves via the package prefix.
2717        let files = [make_file(
2718            "test.proto",
2719            "test.pkg",
2720            vec![msg("Msg"), msg("Other")],
2721            vec![],
2722        )];
2723        let config = CodeGenConfig {
2724            extern_paths: vec![
2725                (".test.pkg".into(), "::pkg_crate".into()),
2726                (".test.pkg.Msg".into(), "::ext_crate::Msg".into()),
2727            ],
2728            ..Default::default()
2729        };
2730        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2731        assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
2732        assert_eq!(ctx.rust_type(".test.pkg.Other"), Some("::pkg_crate::Other"));
2733    }
2734
2735    #[test]
2736    fn test_extern_path_nested_type_inherits_per_type_override() {
2737        // A per-type override of a parent message cascades to its nested
2738        // types via the snake_case module of the overridden path.
2739        let outer = msg_with_nested("Outer", vec![msg("Inner")]);
2740        let files = [make_file("test.proto", "test.pkg", vec![outer], vec![])];
2741        let config = CodeGenConfig {
2742            extern_paths: vec![(".test.pkg.Outer".into(), "::ext::Outer".into())],
2743            ..Default::default()
2744        };
2745        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2746        assert_eq!(ctx.rust_type(".test.pkg.Outer"), Some("::ext::Outer"));
2747        assert_eq!(
2748            ctx.rust_type(".test.pkg.Outer.Inner"),
2749            Some("::ext::outer::Inner")
2750        );
2751    }
2752
2753    #[test]
2754    fn test_extern_path_exact_per_type_enum() {
2755        let files = [make_file(
2756            "test.proto",
2757            "test.pkg",
2758            vec![],
2759            vec![enum_desc("Status")],
2760        )];
2761        let config = CodeGenConfig {
2762            extern_paths: vec![(".test.pkg.Status".into(), "::ext_crate::Status".into())],
2763            ..Default::default()
2764        };
2765        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2766        assert_eq!(
2767            ctx.rust_type(".test.pkg.Status"),
2768            Some("::ext_crate::Status")
2769        );
2770    }
2771
2772    #[test]
2773    fn test_extern_path_package_prefix_still_resolves() {
2774        // Guard: package-prefix mappings (the only historically-supported
2775        // form) must keep resolving exactly as before.
2776        let files = [make_file(
2777            "test.proto",
2778            "test.pkg",
2779            vec![msg("Msg")],
2780            vec![],
2781        )];
2782        let config = CodeGenConfig {
2783            extern_paths: vec![(".test.pkg".into(), "::pkg_crate".into())],
2784            ..Default::default()
2785        };
2786        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2787        assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::pkg_crate::Msg"));
2788    }
2789
2790    #[test]
2791    fn test_extern_path_per_type_does_not_affect_unmapped_type() {
2792        // Guard: a per-type entry must not leak onto an unrelated type.
2793        let files = [make_file(
2794            "test.proto",
2795            "test.pkg",
2796            vec![msg("Msg"), msg("Other")],
2797            vec![],
2798        )];
2799        let config = CodeGenConfig {
2800            extern_paths: vec![(".test.pkg.Msg".into(), "::ext_crate::Msg".into())],
2801            ..Default::default()
2802        };
2803        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2804        assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
2805        // `Other` has no entry — resolves locally.
2806        assert_eq!(ctx.rust_type(".test.pkg.Other"), Some("test::pkg::Other"));
2807    }
2808
2809    #[test]
2810    fn test_keyword_package_segment_in_type_map() {
2811        // Proto package `google.type` — the type map stores plain string paths.
2812        // Keyword escaping happens at the token level, not in the type map.
2813        let files = [make_file(
2814            "latlng.proto",
2815            "google.type",
2816            vec![msg("LatLng")],
2817            vec![],
2818        )];
2819        let config = CodeGenConfig::default();
2820        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2821        assert_eq!(
2822            ctx.rust_type(".google.type.LatLng"),
2823            Some("google::type::LatLng")
2824        );
2825    }
2826
2827    #[test]
2828    fn test_keyword_package_relative_same_package() {
2829        let files = [make_file(
2830            "latlng.proto",
2831            "google.type",
2832            vec![msg("LatLng"), msg("Expr")],
2833            vec![],
2834        )];
2835        let config = CodeGenConfig::default();
2836        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2837        // Same-package reference: just the type name (no module prefix).
2838        assert_eq!(
2839            ctx.rust_type_relative(".google.type.LatLng", "google.type", 0),
2840            Some("LatLng".into())
2841        );
2842    }
2843
2844    #[test]
2845    fn test_keyword_package_cross_package() {
2846        let files = [
2847            make_file("latlng.proto", "google.type", vec![msg("LatLng")], vec![]),
2848            make_file("svc.proto", "google.cloud", vec![msg("Service")], vec![]),
2849        ];
2850        let config = CodeGenConfig::default();
2851        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2852        // Cross-package: relative path via super:: (keyword escaping at token level).
2853        // From google.cloud, go up one (past "cloud"), then into "type".
2854        assert_eq!(
2855            ctx.rust_type_relative(".google.type.LatLng", "google.cloud", 0),
2856            Some("super::type::LatLng".into())
2857        );
2858    }
2859
2860    #[test]
2861    fn test_keyword_nested_message_module() {
2862        // Message named "Type" → module "type" in type map.
2863        let outer = msg_with_nested("Type", vec![msg("Inner")]);
2864        let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
2865        let config = CodeGenConfig::default();
2866        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2867        assert_eq!(ctx.rust_type(".pkg.Type"), Some("pkg::Type"));
2868        assert_eq!(ctx.rust_type(".pkg.Type.Inner"), Some("pkg::type::Inner"));
2869    }
2870
2871    #[test]
2872    fn test_unknown_type_returns_none() {
2873        let files = [make_file("test.proto", "pkg", vec![msg("Foo")], vec![])];
2874        let config = CodeGenConfig::default();
2875        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2876        assert_eq!(ctx.rust_type(".pkg.Unknown"), None);
2877    }
2878
2879    // ── Relative type resolution tests ───────────────────────────────────
2880
2881    #[test]
2882    fn test_relative_same_package_top_level() {
2883        let files = [make_file("a.proto", "pkg", vec![msg("Foo")], vec![])];
2884        let config = CodeGenConfig::default();
2885        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2886        // From top-level in same package: just the type name.
2887        assert_eq!(
2888            ctx.rust_type_relative(".pkg.Foo", "pkg", 0),
2889            Some("Foo".into())
2890        );
2891    }
2892
2893    #[test]
2894    fn test_relative_cross_package() {
2895        let files = [
2896            make_file("a.proto", "pkg_a", vec![msg("Foo")], vec![]),
2897            make_file("b.proto", "pkg_b", vec![msg("Bar")], vec![]),
2898        ];
2899        let config = CodeGenConfig::default();
2900        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2901        // Cross-package: relative via super:: (up one from pkg_b, into pkg_a).
2902        assert_eq!(
2903            ctx.rust_type_relative(".pkg_a.Foo", "pkg_b", 0),
2904            Some("super::pkg_a::Foo".into())
2905        );
2906    }
2907
2908    #[test]
2909    fn test_relative_no_package() {
2910        let files = [make_file("a.proto", "", vec![msg("Foo")], vec![])];
2911        let config = CodeGenConfig::default();
2912        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2913        assert_eq!(ctx.rust_type_relative(".Foo", "", 0), Some("Foo".into()));
2914    }
2915
2916    #[test]
2917    fn test_relative_unknown_returns_none() {
2918        let files = [make_file("a.proto", "pkg", vec![msg("Foo")], vec![])];
2919        let config = CodeGenConfig::default();
2920        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2921        assert_eq!(ctx.rust_type_relative(".pkg.Unknown", "pkg", 0), None);
2922    }
2923
2924    #[test]
2925    fn test_relative_dotted_package() {
2926        let files = [make_file("a.proto", "my.pkg", vec![msg("Foo")], vec![])];
2927        let config = CodeGenConfig::default();
2928        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2929        assert_eq!(
2930            ctx.rust_type_relative(".my.pkg.Foo", "my.pkg", 0),
2931            Some("Foo".into())
2932        );
2933    }
2934
2935    #[test]
2936    fn test_relative_cross_dotted_packages() {
2937        let files = [
2938            make_file(
2939                "timestamp.proto",
2940                "google.protobuf",
2941                vec![msg("Timestamp")],
2942                vec![],
2943            ),
2944            make_file(
2945                "test.proto",
2946                "protobuf_test_messages.proto3",
2947                vec![msg("TestAllTypesProto3")],
2948                vec![],
2949            ),
2950        ];
2951        let config = CodeGenConfig::default();
2952        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2953
2954        // Cross-package: relative via super:: (no common prefix, up 2 levels).
2955        assert_eq!(
2956            ctx.rust_type_relative(
2957                ".google.protobuf.Timestamp",
2958                "protobuf_test_messages.proto3",
2959                0,
2960            ),
2961            Some("super::super::google::protobuf::Timestamp".into())
2962        );
2963    }
2964
2965    #[test]
2966    fn test_relative_nested_type_from_same_package() {
2967        // Referencing Outer.Inner from the same package.
2968        let outer = msg_with_nested("Outer", vec![msg("Inner")]);
2969        let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
2970        let config = CodeGenConfig::default();
2971        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2972
2973        // Same package: strips the package prefix, keeps module path.
2974        assert_eq!(
2975            ctx.rust_type_relative(".pkg.Outer.Inner", "pkg", 0),
2976            Some("outer::Inner".into())
2977        );
2978    }
2979
2980    #[test]
2981    fn test_nested_module_avoids_the_type_names_of_its_scope() {
2982        // `item` declares `struct item`, so its nested types are in `item_`.
2983        // In `Outer`, the enum `mode` takes the module name of `Mode`.
2984        let item = msg_with_nested("item", vec![msg("Inner")]);
2985        let outer = msg_with_nested_and_enums(
2986            "Outer",
2987            vec![
2988                msg_with_nested("leaf", vec![msg("Deep")]),
2989                msg_with_nested("Mode", vec![msg("Detail")]),
2990            ],
2991            vec![enum_desc("mode")],
2992        );
2993        let files = [make_file("test.proto", "pkg", vec![item, outer], vec![])];
2994        let config = CodeGenConfig::default();
2995        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
2996
2997        assert_eq!(ctx.rust_type(".pkg.item"), Some("pkg::item"));
2998        assert_eq!(ctx.rust_type(".pkg.item.Inner"), Some("pkg::item_::Inner"));
2999        assert_eq!(
3000            ctx.rust_type(".pkg.Outer.leaf.Deep"),
3001            Some("pkg::outer::leaf_::Deep")
3002        );
3003        assert_eq!(
3004            ctx.rust_type(".pkg.Outer.Mode.Detail"),
3005            Some("pkg::outer::mode_::Detail")
3006        );
3007        assert_eq!(ctx.nested_module_name("pkg", "item"), "item_");
3008        assert_eq!(ctx.message_module_name("pkg.Outer"), "outer");
3009        assert_eq!(ctx.message_module_name("pkg.Outer.leaf"), "leaf_");
3010    }
3011
3012    #[test]
3013    fn test_nested_module_of_a_prefixed_type_keeps_its_name() {
3014        // With prefix `Pb` the struct is `Pbitem`, and `item` is free.
3015        let item = msg_with_nested("item", vec![msg("Inner")]);
3016        let files = [make_file("test.proto", "pkg", vec![item], vec![])];
3017        let config = CodeGenConfig {
3018            type_name_prefix: "Pb".to_string(),
3019            ..Default::default()
3020        };
3021        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3022        assert_eq!(ctx.rust_type(".pkg.item.Inner"), Some("pkg::item::PbInner"));
3023    }
3024
3025    #[test]
3026    fn test_nested_module_named_after_a_path_keyword_gets_a_suffix() {
3027        let files = [make_file(
3028            "test.proto",
3029            "pkg",
3030            vec![
3031                msg_with_nested("Crate", vec![msg("Inner")]),
3032                msg_with_nested("Self", vec![msg("Inner")]),
3033            ],
3034            vec![],
3035        )];
3036        let config = CodeGenConfig::default();
3037        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3038        assert_eq!(
3039            ctx.rust_type(".pkg.Crate.Inner"),
3040            Some("pkg::crate_::Inner")
3041        );
3042        assert_eq!(ctx.rust_type(".pkg.Self"), Some("pkg::Self_"));
3043        assert_eq!(ctx.rust_type(".pkg.Self.Inner"), Some("pkg::self_::Inner"));
3044    }
3045
3046    #[test]
3047    fn test_reserved_module_names_do_not_depend_on_the_config() {
3048        let files = [make_file(
3049            "test.proto",
3050            "pkg",
3051            vec![
3052                msg_with_nested("Arbitrary", vec![msg("Inner")]),
3053                msg_with_nested("Oneof", vec![msg("Inner")]),
3054                msg_with_nested("Outer", vec![msg_with_nested("Oneof", vec![msg("Inner")])]),
3055            ],
3056            vec![],
3057        )];
3058        // `generate_arbitrary` and `generate_views` are at their defaults.
3059        let config = CodeGenConfig::default();
3060        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3061        assert_eq!(
3062            ctx.rust_type(".pkg.Arbitrary.Inner"),
3063            Some("pkg::arbitrary_::Inner")
3064        );
3065        assert_eq!(
3066            ctx.rust_type(".pkg.Oneof.Inner"),
3067            Some("pkg::oneof_::Inner")
3068        );
3069        // `oneof` is taken at package level only.
3070        assert_eq!(
3071            ctx.rust_type(".pkg.Outer.Oneof.Inner"),
3072            Some("pkg::outer::oneof::Inner")
3073        );
3074    }
3075
3076    #[test]
3077    fn test_top_level_module_avoids_an_enum_in_another_file() {
3078        let mode = || msg_with_nested("Mode", vec![msg("Detail")]);
3079        let same_file = [make_file(
3080            "a.proto",
3081            "pkg",
3082            vec![mode()],
3083            vec![enum_desc("mode")],
3084        )];
3085        let two_files = [
3086            make_file("a.proto", "pkg", vec![mode()], vec![]),
3087            make_file("b.proto", "pkg", vec![], vec![enum_desc("mode")]),
3088        ];
3089        let config = CodeGenConfig::default();
3090        for files in [&same_file[..], &two_files[..]] {
3091            let ctx = CodeGenContext::new(files, &config, &config.extern_paths);
3092            assert_eq!(
3093                ctx.rust_type(".pkg.Mode.Detail"),
3094                Some("pkg::mode_::Detail")
3095            );
3096        }
3097    }
3098
3099    #[test]
3100    fn test_module_avoids_a_sub_package_named_after_a_path_keyword() {
3101        // The sub-package `pkg.crate` is the module `crate_`.
3102        let files = [
3103            make_file(
3104                "a.proto",
3105                "pkg",
3106                vec![msg_with_nested("Crate", vec![msg("Inner")])],
3107                vec![],
3108            ),
3109            make_file("b.proto", "pkg.crate", vec![msg("Thing")], vec![]),
3110            // A sub-package named `arbitrary` keeps that module name.
3111            make_file(
3112                "c.proto",
3113                "pkg",
3114                vec![msg_with_nested("Arbitrary", vec![msg("Inner")])],
3115                vec![],
3116            ),
3117            make_file("d.proto", "pkg.arbitrary", vec![msg("Thing")], vec![]),
3118        ];
3119        let config = CodeGenConfig::default();
3120        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3121        assert_eq!(
3122            ctx.rust_type(".pkg.Crate.Inner"),
3123            Some("pkg::crate__::Inner")
3124        );
3125        assert_eq!(
3126            ctx.rust_type(".pkg.Arbitrary.Inner"),
3127            Some("pkg::arbitrary_::Inner")
3128        );
3129    }
3130
3131    #[test]
3132    fn test_extern_package_nested_types_use_the_renamed_modules() {
3133        let files = [
3134            make_file(
3135                "other.proto",
3136                "other",
3137                vec![
3138                    msg_with_nested("item", vec![msg("Inner")]),
3139                    msg_with_nested("Crate", vec![msg("Inner")]),
3140                    msg_with_nested("Outer", vec![msg_with_nested("leaf", vec![msg("Deep")])]),
3141                ],
3142                vec![],
3143            ),
3144            make_file("local.proto", "local", vec![msg("User")], vec![]),
3145        ];
3146        let config = CodeGenConfig {
3147            extern_paths: vec![(".other".into(), "::ext::other".into())],
3148            ..Default::default()
3149        };
3150        let ctx = CodeGenContext::for_generate(&files, &["local.proto".to_string()], &config);
3151        assert_eq!(
3152            ctx.rust_type(".other.item.Inner"),
3153            Some("::ext::other::item_::Inner")
3154        );
3155        assert_eq!(
3156            ctx.rust_type(".other.Crate.Inner"),
3157            Some("::ext::other::crate_::Inner")
3158        );
3159        assert_eq!(
3160            ctx.rust_type(".other.Outer.leaf.Deep"),
3161            Some("::ext::other::outer::leaf_::Deep")
3162        );
3163        // The `__buffa` trees are entered at the package and use the same
3164        // module path.
3165        let split = ctx
3166            .rust_type_relative_split(".other.item.Inner", "local", 0)
3167            .expect("type resolves");
3168        assert_eq!(split.to_package, "::ext::other");
3169        assert_eq!(split.within_package, "item_::Inner");
3170    }
3171
3172    #[test]
3173    fn test_exact_extern_override_nested_types_use_the_renamed_module() {
3174        let files = [make_file(
3175            "test.proto",
3176            "pkg",
3177            vec![
3178                msg_with_nested("item", vec![msg("Inner")]),
3179                msg_with_nested("Crate", vec![msg("Inner")]),
3180                msg_with_nested("Outer", vec![msg_with_nested("leaf", vec![msg("Deep")])]),
3181            ],
3182            vec![],
3183        )];
3184        let config = CodeGenConfig {
3185            extern_paths: vec![
3186                (".pkg.item".into(), "::ext::item".into()),
3187                (".pkg.Crate".into(), "::ext::Crate".into()),
3188                (".pkg.Outer.leaf".into(), "::ext::outer::leaf".into()),
3189            ],
3190            ..Default::default()
3191        };
3192        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3193        assert_eq!(
3194            ctx.rust_type(".pkg.item.Inner"),
3195            Some("::ext::item_::Inner")
3196        );
3197        assert_eq!(
3198            ctx.rust_type(".pkg.Crate.Inner"),
3199            Some("::ext::crate_::Inner")
3200        );
3201        assert_eq!(
3202            ctx.rust_type(".pkg.Outer.leaf.Deep"),
3203            Some("::ext::outer::leaf_::Deep")
3204        );
3205    }
3206
3207    #[test]
3208    fn test_relative_shared_prefix_not_confused() {
3209        let files = [
3210            make_file("ab.proto", "a.b", vec![msg("Msg1")], vec![]),
3211            make_file("abc.proto", "a.bc", vec![msg("Msg2")], vec![]),
3212        ];
3213        let config = CodeGenConfig::default();
3214        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3215
3216        // `a.b.Msg1` from `a.bc` context: common prefix "a", up 1, into "b".
3217        assert_eq!(
3218            ctx.rust_type_relative(".a.b.Msg1", "a.bc", 0),
3219            Some("super::b::Msg1".into())
3220        );
3221        // `a.bc.Msg2` from `a.b` context: common prefix "a", up 1, into "bc".
3222        assert_eq!(
3223            ctx.rust_type_relative(".a.bc.Msg2", "a.b", 0),
3224            Some("super::bc::Msg2".into())
3225        );
3226    }
3227
3228    // ── Nesting depth tests ────────────────────────────────────────────
3229
3230    #[test]
3231    fn test_relative_cross_package_nesting_1() {
3232        // Simulates a nested message (inside a `pub mod`) referencing a type
3233        // from a sibling package. E.g., account.business.admin.v1 nested msg
3234        // referencing account.business.v1.Business.Status.
3235        let outer = msg_with_nested_and_enums("Business", vec![], vec![enum_desc("Status")]);
3236        let files = [
3237            make_file("admin.proto", "a.b.admin.v1", vec![msg("Svc")], vec![]),
3238            make_file("biz.proto", "a.b.v1", vec![outer], vec![]),
3239        ];
3240        let config = CodeGenConfig::default();
3241        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3242
3243        // nesting=0 (top-level struct in admin.v1): up 2 (v1→admin), into v1
3244        assert_eq!(
3245            ctx.rust_type_relative(".a.b.v1.Business.Status", "a.b.admin.v1", 0),
3246            Some("super::super::v1::business::Status".into())
3247        );
3248        // nesting=1 (inside a nested message module): one extra super::
3249        assert_eq!(
3250            ctx.rust_type_relative(".a.b.v1.Business.Status", "a.b.admin.v1", 1),
3251            Some("super::super::super::v1::business::Status".into())
3252        );
3253    }
3254
3255    #[test]
3256    fn test_relative_same_package_nesting_1() {
3257        // Nested message referencing a sibling type in the same package.
3258        let files = [make_file(
3259            "test.proto",
3260            "pkg",
3261            vec![msg("Foo"), msg("Bar")],
3262            vec![],
3263        )];
3264        let config = CodeGenConfig::default();
3265        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3266
3267        // nesting=0: same package, just the name
3268        assert_eq!(
3269            ctx.rust_type_relative(".pkg.Foo", "pkg", 0),
3270            Some("Foo".into())
3271        );
3272        // nesting=1: inside a message module, needs one super::
3273        assert_eq!(
3274            ctx.rust_type_relative(".pkg.Foo", "pkg", 1),
3275            Some("super::Foo".into())
3276        );
3277        // nesting=2: doubly nested
3278        assert_eq!(
3279            ctx.rust_type_relative(".pkg.Foo", "pkg", 2),
3280            Some("super::super::Foo".into())
3281        );
3282    }
3283
3284    // ── Extern path tests ─────────────────────────────────────────────
3285
3286    #[test]
3287    fn test_resolve_file_extern_exact_match_only() {
3288        let mappings = [(
3289            "google/protobuf/descriptor.proto".to_string(),
3290            "::buffa_descriptor::generated::descriptor".to_string(),
3291        )];
3292        // Exact file path matches.
3293        assert_eq!(
3294            resolve_file_extern("google/protobuf/descriptor.proto", &mappings),
3295            Some("::buffa_descriptor::generated::descriptor"),
3296        );
3297        // No prefix matching — a sibling file in the same directory does
3298        // not match (its types live in a different generated module).
3299        assert_eq!(
3300            resolve_file_extern("google/protobuf/timestamp.proto", &mappings),
3301            None,
3302        );
3303        // No suffix matching either.
3304        assert_eq!(
3305            resolve_file_extern("vendor/google/protobuf/descriptor.proto", &mappings),
3306            None,
3307        );
3308    }
3309
3310    #[test]
3311    fn test_resolve_extern_prefix_exact_match() {
3312        let result = resolve_extern_prefix(
3313            "my.common",
3314            &[(".my.common".into(), "::common_protos".into())],
3315        );
3316        assert_eq!(result, Some("::common_protos".into()));
3317    }
3318
3319    #[test]
3320    fn test_resolve_extern_prefix_sub_package() {
3321        let result = resolve_extern_prefix(
3322            "my.common.sub",
3323            &[(".my.common".into(), "::common_protos".into())],
3324        );
3325        assert_eq!(result, Some("::common_protos::sub".into()));
3326    }
3327
3328    #[test]
3329    fn test_resolve_extern_prefix_no_match() {
3330        let result = resolve_extern_prefix(
3331            "other.pkg",
3332            &[(".my.common".into(), "::common_protos".into())],
3333        );
3334        assert_eq!(result, None);
3335    }
3336
3337    #[test]
3338    fn test_resolve_extern_prefix_partial_name_no_match() {
3339        // ".my.common" should not match ".my.commonext"
3340        let result = resolve_extern_prefix(
3341            "my.commonext",
3342            &[(".my.common".into(), "::common_protos".into())],
3343        );
3344        assert_eq!(result, None);
3345    }
3346
3347    #[test]
3348    fn test_resolve_extern_prefix_longest_match_wins() {
3349        // When multiple prefixes match, the longest one should win.
3350        let result = resolve_extern_prefix(
3351            "my.common.sub",
3352            &[
3353                (".my".into(), "::crate_a".into()),
3354                (".my.common".into(), "::crate_b".into()),
3355            ],
3356        );
3357        assert_eq!(result, Some("::crate_b::sub".into()));
3358    }
3359
3360    #[test]
3361    fn test_resolve_extern_prefix_catchall() {
3362        let result = resolve_extern_prefix("greet.v1", &[(".".into(), "crate::proto".into())]);
3363        assert_eq!(result, Some("crate::proto::greet::v1".into()));
3364    }
3365
3366    #[test]
3367    fn test_resolve_extern_prefix_catchall_empty_pkg() {
3368        // Empty package with `.` catch-all hits the exact-match branch
3369        // (dotted == "." == proto_prefix) and returns the root as-is.
3370        let result = resolve_extern_prefix("", &[(".".into(), "crate::proto".into())]);
3371        assert_eq!(result, Some("crate::proto".into()));
3372    }
3373
3374    #[test]
3375    fn test_resolve_extern_prefix_catchall_longest_wins() {
3376        // `.` catch-all is the shortest possible prefix; any more-specific
3377        // mapping (including the auto-injected WKT mapping) takes priority.
3378        let result = resolve_extern_prefix(
3379            "google.protobuf",
3380            &[
3381                (".".into(), "crate::proto".into()),
3382                (
3383                    ".google.protobuf".into(),
3384                    "::buffa_types::google::protobuf".into(),
3385                ),
3386            ],
3387        );
3388        assert_eq!(result, Some("::buffa_types::google::protobuf".into()));
3389    }
3390
3391    #[test]
3392    fn test_resolve_extern_prefix_catchall_keyword_package() {
3393        // Keyword segments stay unescaped at the string level; escaping to
3394        // `r#type` happens later in `idents::rust_path_to_tokens`.
3395        let result = resolve_extern_prefix("google.type", &[(".".into(), "crate::proto".into())]);
3396        assert_eq!(result, Some("crate::proto::google::type".into()));
3397    }
3398
3399    // ── resolve_extern_type — per-type FQN resolution (issue #111) ─────────
3400
3401    #[test]
3402    fn test_resolve_extern_type_exact_match() {
3403        // An exact entry for the type FQN is the full Rust path verbatim.
3404        let result = resolve_extern_type(
3405            ".google.protobuf.Timestamp",
3406            &[(
3407                ".google.protobuf.Timestamp".into(),
3408                "::pbjson_types::Timestamp".into(),
3409            )],
3410        );
3411        assert_eq!(result, Some("::pbjson_types::Timestamp".into()));
3412    }
3413
3414    #[test]
3415    fn test_resolve_extern_type_escapes_a_prefix_mapped_type_name() {
3416        // The crate that owns the package declares `bool` as `bool_`.
3417        let prefix = [(".other.v1".to_string(), "::other::v1".to_string())];
3418        assert_eq!(
3419            resolve_extern_type(".other.v1.bool", &prefix),
3420            Some("::other::v1::bool_".into())
3421        );
3422        assert_eq!(
3423            resolve_extern_type(".other.v1.type", &prefix),
3424            Some("::other::v1::type_".into())
3425        );
3426        assert_eq!(
3427            resolve_extern_type(".other.v1.Outer.Self", &prefix),
3428            Some("::other::v1::outer::Self_".into())
3429        );
3430        // An exact entry is the caller's own path, used as written.
3431        assert_eq!(
3432            resolve_extern_type(
3433                ".other.v1.bool",
3434                &[(".other.v1.bool".into(), "::other::Flag".into())]
3435            ),
3436            Some("::other::Flag".into())
3437        );
3438    }
3439
3440    #[test]
3441    fn test_resolve_extern_type_exact_wins_over_prefix() {
3442        // Exact-match-first: the per-type entry beats a covering package entry.
3443        let result = resolve_extern_type(
3444            ".my.pkg.Msg",
3445            &[
3446                (".my.pkg".into(), "::pkg_crate".into()),
3447                (".my.pkg.Msg".into(), "::ext_crate::Msg".into()),
3448            ],
3449        );
3450        assert_eq!(result, Some("::ext_crate::Msg".into()));
3451    }
3452
3453    #[test]
3454    fn test_resolve_extern_type_package_prefix_appends_type() {
3455        // A package prefix yields `<rust_prefix>::<sub modules>::<TypeName>`,
3456        // matching what resolve_extern_prefix + the type name would build.
3457        let result = resolve_extern_type(
3458            ".my.common.sub.Msg",
3459            &[(".my.common".into(), "::common_protos".into())],
3460        );
3461        assert_eq!(result, Some("::common_protos::sub::Msg".into()));
3462    }
3463
3464    #[test]
3465    fn test_resolve_extern_type_catchall() {
3466        let result = resolve_extern_type(".greet.v1.Hello", &[(".".into(), "crate::proto".into())]);
3467        assert_eq!(result, Some("crate::proto::greet::v1::Hello".into()));
3468    }
3469
3470    #[test]
3471    fn test_resolve_extern_type_no_match() {
3472        let result = resolve_extern_type(
3473            ".other.pkg.Msg",
3474            &[(".my.common".into(), "::common_protos".into())],
3475        );
3476        assert_eq!(result, None);
3477    }
3478
3479    #[test]
3480    fn test_resolve_extern_type_partial_name_no_match() {
3481        // ".my.common" must not match ".my.commonext.Msg" (dot-boundary).
3482        let result = resolve_extern_type(
3483            ".my.commonext.Msg",
3484            &[(".my.common".into(), "::common_protos".into())],
3485        );
3486        assert_eq!(result, None);
3487    }
3488
3489    // ── rust_type_relative_split — extern branch ────────────────────────
3490
3491    #[test]
3492    fn test_split_extern_top_level() {
3493        let outer = msg_with_nested("Value", vec![msg("Inner")]);
3494        let files = [make_file(
3495            "struct.proto",
3496            "google.protobuf",
3497            vec![outer],
3498            vec![],
3499        )];
3500        let config = CodeGenConfig::default();
3501        let extern_paths = vec![(
3502            ".google.protobuf".into(),
3503            "::buffa_types::google::protobuf".into(),
3504        )];
3505        let ctx = CodeGenContext::new(&files, &config, &extern_paths);
3506
3507        let split = ctx
3508            .rust_type_relative_split(".google.protobuf.Value", "my.pkg", 3)
3509            .expect("type resolves");
3510        assert!(split.is_extern);
3511        // Extern path is absolute → nesting irrelevant.
3512        assert_eq!(split.to_package, "::buffa_types::google::protobuf");
3513        assert_eq!(split.within_package, "Value");
3514    }
3515
3516    #[test]
3517    fn test_split_extern_nested_type() {
3518        // Nested `.google.protobuf.Value.Inner` →
3519        // extern path `::buffa_types::google::protobuf::value::Inner`.
3520        // Segment-count slice: 2 within-package segments → cut after the
3521        // extern module prefix.
3522        let outer = msg_with_nested("Value", vec![msg("Inner")]);
3523        let files = [make_file(
3524            "struct.proto",
3525            "google.protobuf",
3526            vec![outer],
3527            vec![],
3528        )];
3529        let config = CodeGenConfig::default();
3530        let extern_paths = vec![(
3531            ".google.protobuf".into(),
3532            "::buffa_types::google::protobuf".into(),
3533        )];
3534        let ctx = CodeGenContext::new(&files, &config, &extern_paths);
3535
3536        let split = ctx
3537            .rust_type_relative_split(".google.protobuf.Value.Inner", "my.pkg", 0)
3538            .expect("nested type resolves");
3539        assert!(split.is_extern);
3540        assert_eq!(split.to_package, "::buffa_types::google::protobuf");
3541        assert_eq!(split.within_package, "value::Inner");
3542    }
3543
3544    #[test]
3545    fn test_split_per_type_extern_override() {
3546        // Per-type override (issue #111): the `__buffa::` boundary recovery must
3547        // still split the override path at the package/within-package seam, so
3548        // callers compose `<to_package>::__buffa::view::<within_package>`
3549        // correctly. Both the overridden type and its nested children are
3550        // exercised.
3551        let outer = msg_with_nested("Outer", vec![msg("Inner")]);
3552        let files = [make_file("custom.proto", "my.pkg", vec![outer], vec![])];
3553        let config = CodeGenConfig {
3554            extern_paths: vec![(".my.pkg.Outer".into(), "::ext::custom::Outer".into())],
3555            ..Default::default()
3556        };
3557        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3558
3559        let split = ctx
3560            .rust_type_relative_split(".my.pkg.Outer", "other.pkg", 2)
3561            .expect("overridden type resolves");
3562        assert!(split.is_extern);
3563        assert_eq!(split.to_package, "::ext::custom");
3564        assert_eq!(split.within_package, "Outer");
3565
3566        // The nested type inherits the override's module, and the seam is
3567        // recovered the same way (2 within-package segments stripped).
3568        let nested = ctx
3569            .rust_type_relative_split(".my.pkg.Outer.Inner", "other.pkg", 0)
3570            .expect("nested type resolves");
3571        assert!(nested.is_extern);
3572        assert_eq!(nested.to_package, "::ext::custom");
3573        assert_eq!(nested.within_package, "outer::Inner");
3574    }
3575
3576    #[test]
3577    fn test_extern_path_top_level_message() {
3578        let files = [make_file(
3579            "common.proto",
3580            "my.common",
3581            vec![msg("SharedMsg")],
3582            vec![],
3583        )];
3584        let config = CodeGenConfig {
3585            extern_paths: vec![(".my.common".into(), "::common_protos".into())],
3586            ..Default::default()
3587        };
3588        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3589        assert_eq!(
3590            ctx.rust_type(".my.common.SharedMsg"),
3591            Some("::common_protos::SharedMsg")
3592        );
3593    }
3594
3595    #[test]
3596    fn test_extern_path_nested_message() {
3597        let files = [make_file(
3598            "common.proto",
3599            "my.common",
3600            vec![msg_with_nested("Outer", vec![msg("Inner")])],
3601            vec![],
3602        )];
3603        let config = CodeGenConfig {
3604            extern_paths: vec![(".my.common".into(), "::common_protos".into())],
3605            ..Default::default()
3606        };
3607        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3608        assert_eq!(
3609            ctx.rust_type(".my.common.Outer"),
3610            Some("::common_protos::Outer")
3611        );
3612        assert_eq!(
3613            ctx.rust_type(".my.common.Outer.Inner"),
3614            Some("::common_protos::outer::Inner")
3615        );
3616    }
3617
3618    #[test]
3619    fn test_extern_path_nested_types_use_deconflicted_module() {
3620        // Mirrors pb.lyft.Money.{Currency,Breakdown} vs sub-package pb.lyft.money.
3621        let money =
3622            msg_with_nested_and_enums("Money", vec![msg("Breakdown")], vec![enum_desc("Currency")]);
3623        let files = [
3624            make_file("lyft_money.proto", "pb.lyft", vec![money], vec![]),
3625            make_file("money.proto", "pb.lyft.money", vec![msg("Money")], vec![]),
3626            make_file(
3627                "users.proto",
3628                "pb.lyft.users",
3629                vec![msg("DailyTotalFares")],
3630                vec![],
3631            ),
3632        ];
3633        let config = CodeGenConfig {
3634            extern_paths: vec![(".pb.lyft".into(), "::idl_pb_lyft::pb::lyft".into())],
3635            ..Default::default()
3636        };
3637        let ctx = CodeGenContext::for_generate(&files, &["users.proto".to_string()], &config);
3638        assert_eq!(
3639            ctx.rust_type(".pb.lyft.Money.Currency"),
3640            Some("::idl_pb_lyft::pb::lyft::money_::Currency")
3641        );
3642        assert_eq!(
3643            ctx.rust_type(".pb.lyft.Money.Breakdown"),
3644            Some("::idl_pb_lyft::pb::lyft::money_::Breakdown")
3645        );
3646    }
3647
3648    #[test]
3649    fn test_extern_path_enum() {
3650        let files = [make_file(
3651            "common.proto",
3652            "my.common",
3653            vec![],
3654            vec![enum_desc("Status")],
3655        )];
3656        let config = CodeGenConfig {
3657            extern_paths: vec![(".my.common".into(), "::common_protos".into())],
3658            ..Default::default()
3659        };
3660        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3661        assert_eq!(
3662            ctx.rust_type(".my.common.Status"),
3663            Some("::common_protos::Status")
3664        );
3665    }
3666
3667    #[test]
3668    fn test_extern_path_does_not_affect_other_packages() {
3669        let files = [
3670            make_file("common.proto", "my.common", vec![msg("SharedMsg")], vec![]),
3671            make_file(
3672                "service.proto",
3673                "my.service",
3674                vec![msg("MyService")],
3675                vec![],
3676            ),
3677        ];
3678        let config = CodeGenConfig {
3679            extern_paths: vec![(".my.common".into(), "::common_protos".into())],
3680            ..Default::default()
3681        };
3682        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3683        // Extern type uses absolute path.
3684        assert_eq!(
3685            ctx.rust_type(".my.common.SharedMsg"),
3686            Some("::common_protos::SharedMsg")
3687        );
3688        // Non-extern type uses normal package-derived path.
3689        assert_eq!(
3690            ctx.rust_type(".my.service.MyService"),
3691            Some("my::service::MyService")
3692        );
3693    }
3694
3695    #[test]
3696    fn test_extern_path_relative_returns_absolute() {
3697        // When an extern type is referenced from another package,
3698        // rust_type_relative should return the full absolute path.
3699        let files = [
3700            make_file("common.proto", "my.common", vec![msg("SharedMsg")], vec![]),
3701            make_file(
3702                "service.proto",
3703                "my.service",
3704                vec![msg("MyService")],
3705                vec![],
3706            ),
3707        ];
3708        let config = CodeGenConfig {
3709            extern_paths: vec![(".my.common".into(), "::common_protos".into())],
3710            ..Default::default()
3711        };
3712        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3713        // Cross-package reference to extern type: absolute path.
3714        assert_eq!(
3715            ctx.rust_type_relative(".my.common.SharedMsg", "my.service", 0),
3716            Some("::common_protos::SharedMsg".into())
3717        );
3718    }
3719
3720    // ── is_enum_closed tests ──────────────────────────────────────────────
3721
3722    #[test]
3723    fn test_is_enum_closed_proto3_default_open() {
3724        let files = [make_file("a.proto", "p", vec![], vec![enum_desc("E")])];
3725        let config = CodeGenConfig::default();
3726        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3727        // proto3 default (make_file has no syntax = proto2/implicit)
3728        // actually make_file doesn't set syntax, so it's proto2 default...
3729        // proto2 default is CLOSED.
3730        assert_eq!(ctx.is_enum_closed(".p.E"), Some(true));
3731    }
3732
3733    #[test]
3734    fn test_is_enum_closed_editions_default_open() {
3735        let files = [editions_file("a.proto", "p", vec![], vec![enum_desc("E")])];
3736        let config = CodeGenConfig::default();
3737        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3738        // Edition 2023 default is OPEN.
3739        assert_eq!(ctx.is_enum_closed(".p.E"), Some(false));
3740    }
3741
3742    #[test]
3743    fn test_is_enum_closed_per_enum_override() {
3744        // This is THE bug: enum with `option features.enum_type = CLOSED`
3745        // in an otherwise-open editions file must be detected as closed.
3746        let files = [editions_file(
3747            "a.proto",
3748            "p",
3749            vec![],
3750            vec![enum_desc("Open"), enum_with_closed_feature("Closed")],
3751        )];
3752        let config = CodeGenConfig::default();
3753        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3754        assert_eq!(ctx.is_enum_closed(".p.Open"), Some(false));
3755        assert_eq!(ctx.is_enum_closed(".p.Closed"), Some(true));
3756    }
3757
3758    #[test]
3759    fn test_is_enum_closed_nested_per_enum_override() {
3760        // Feature resolution through file → message → enum.
3761        let files = [editions_file(
3762            "a.proto",
3763            "p",
3764            vec![msg_with_nested_and_enums(
3765                "M",
3766                vec![],
3767                vec![enum_with_closed_feature("Inner")],
3768            )],
3769            vec![],
3770        )];
3771        let config = CodeGenConfig::default();
3772        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3773        assert_eq!(ctx.is_enum_closed(".p.M.Inner"), Some(true));
3774    }
3775
3776    #[test]
3777    fn test_is_enum_closed_unknown_enum_returns_none() {
3778        let files = [editions_file("a.proto", "p", vec![], vec![])];
3779        let config = CodeGenConfig::default();
3780        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
3781        // extern_path or missing enum → None (caller falls back).
3782        assert_eq!(ctx.is_enum_closed(".other.Unknown"), None);
3783    }
3784
3785    #[test]
3786    fn test_for_generate_auto_injects_wkt_mapping() {
3787        // for_generate() must produce the same type_map as generate() uses
3788        // internally — including the auto-injected WKT extern_path.
3789        let ts_msg = DescriptorProto {
3790            name: Some("Timestamp".into()),
3791            ..Default::default()
3792        };
3793        let files = [FileDescriptorProto {
3794            name: Some("google/protobuf/timestamp.proto".into()),
3795            package: Some("google.protobuf".into()),
3796            syntax: Some("proto3".into()),
3797            message_type: vec![ts_msg],
3798            ..Default::default()
3799        }];
3800        let config = CodeGenConfig::default();
3801        // Not generating the WKT file itself → auto-mapping should kick in.
3802        let ctx = CodeGenContext::for_generate(&files, &["other.proto".into()], &config);
3803        assert_eq!(
3804            ctx.rust_type(".google.protobuf.Timestamp"),
3805            Some("::buffa_types::google::protobuf::Timestamp"),
3806            "WKT auto-mapping must be applied via for_generate"
3807        );
3808    }
3809
3810    #[test]
3811    fn test_for_generate_suppresses_wkt_when_generating_wkt() {
3812        // When files_to_generate includes a google.protobuf file (building
3813        // buffa-types itself), the WKT auto-mapping must NOT be applied.
3814        let ts_msg = DescriptorProto {
3815            name: Some("Timestamp".into()),
3816            ..Default::default()
3817        };
3818        let files = [FileDescriptorProto {
3819            name: Some("google/protobuf/timestamp.proto".into()),
3820            package: Some("google.protobuf".into()),
3821            syntax: Some("proto3".into()),
3822            message_type: vec![ts_msg],
3823            ..Default::default()
3824        }];
3825        let config = CodeGenConfig::default();
3826        let ctx = CodeGenContext::for_generate(
3827            &files,
3828            &["google/protobuf/timestamp.proto".into()],
3829            &config,
3830        );
3831        // No extern mapping → local-package path.
3832        assert_eq!(
3833            ctx.rust_type(".google.protobuf.Timestamp"),
3834            Some("google::protobuf::Timestamp")
3835        );
3836    }
3837
3838    // ── matching_attributes tests ──────────────────────────────────────
3839
3840    #[test]
3841    fn test_matching_attributes_catchall() {
3842        // "." matches every type.
3843        let attrs = vec![(".".into(), "#[derive(Foo)]".into())];
3844        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3845        assert!(result.to_string().contains("derive"));
3846    }
3847
3848    #[test]
3849    fn test_matching_attributes_exact_match() {
3850        let attrs = vec![(".my.pkg.MyMessage".into(), "#[derive(Bar)]".into())];
3851        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3852        assert!(result.to_string().contains("derive"));
3853    }
3854
3855    #[test]
3856    fn test_matching_attributes_package_prefix() {
3857        let attrs = vec![(".my.pkg".into(), "#[derive(Baz)]".into())];
3858        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3859        assert!(result.to_string().contains("derive"));
3860    }
3861
3862    #[test]
3863    fn test_matching_attributes_no_partial_segment_match() {
3864        // ".my.pk" must not match ".my.pkg" (partial segment).
3865        let attrs = vec![(".my.pk".into(), "#[derive(Bad)]".into())];
3866        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3867        assert!(result.is_empty());
3868    }
3869
3870    #[test]
3871    fn test_matching_attributes_no_match() {
3872        let attrs = vec![(".other.pkg".into(), "#[derive(Nope)]".into())];
3873        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3874        assert!(result.is_empty());
3875    }
3876
3877    #[test]
3878    fn test_matching_attributes_multiple_accumulate() {
3879        // All matching entries are emitted, not just the first.
3880        let attrs = vec![
3881            (".".into(), "#[derive(A)]".into()),
3882            (".my.pkg".into(), "#[derive(B)]".into()),
3883        ];
3884        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
3885        let s = result.to_string();
3886        assert!(s.contains("A") && s.contains("B"));
3887    }
3888
3889    #[test]
3890    fn test_matching_attributes_invalid_attr_errors() {
3891        // Unparseable attributes surface as a hard error so the user sees
3892        // the problem at build time rather than a silently-dropped attribute.
3893        let attrs = vec![(".".into(), "not valid {{{{".into())];
3894        let err = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap_err();
3895        assert!(matches!(
3896            err,
3897            crate::CodeGenError::InvalidCustomAttribute { .. }
3898        ));
3899    }
3900
3901    /// The `detail` of the error `matching_attributes` gives for `attribute`.
3902    fn attribute_error_detail(attribute: &str) -> String {
3903        let attrs = vec![(".my.pkg".to_string(), attribute.to_string())];
3904        match CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg") {
3905            Err(crate::CodeGenError::InvalidCustomAttribute {
3906                path,
3907                attribute: reported,
3908                detail,
3909            }) => {
3910                assert_eq!(path, ".my.pkg");
3911                assert_eq!(reported, attribute);
3912                detail
3913            }
3914            other => panic!("{attribute:?}: expected InvalidCustomAttribute, got {other:?}"),
3915        }
3916    }
3917
3918    #[test]
3919    fn test_matching_attributes_rejects_tokens_that_are_not_outer_attributes() {
3920        // Each of these lexes as a token stream, so it used to be spliced
3921        // into the generated code as written.
3922        for attribute in [
3923            "serde(skip)",
3924            "pub extra: u32,",
3925            "#[derive(A)] pub extra: u32,",
3926            "#[derive(A)] serde(skip)",
3927            "derive(A) #[derive(B)]",
3928        ] {
3929            assert_eq!(
3930                attribute_error_detail(attribute),
3931                "expected an outer attribute of the form `#[...]`",
3932                "{attribute:?}"
3933            );
3934        }
3935    }
3936
3937    #[test]
3938    fn test_matching_attributes_rejects_an_inner_attribute() {
3939        for attribute in ["#![allow(dead_code)]", "//! Module docs."] {
3940            assert_eq!(
3941                attribute_error_detail(attribute),
3942                "an inner attribute `#![...]` is not accepted; write `#[...]`",
3943                "{attribute:?}"
3944            );
3945        }
3946    }
3947
3948    #[test]
3949    fn test_matching_attributes_rejects_a_string_without_an_attribute() {
3950        for attribute in ["", "  \n"] {
3951            assert_eq!(
3952                attribute_error_detail(attribute),
3953                "expected at least one `#[...]` attribute",
3954                "{attribute:?}"
3955            );
3956        }
3957    }
3958
3959    #[test]
3960    fn test_matching_attributes_multiple_in_one_string() {
3961        // Several `#[...]` attributes in a single string stay valid, and a
3962        // doc comment is an outer attribute.
3963        let attrs = vec![(
3964            ".".into(),
3965            "/// Doc.\n#[derive(A)] #[serde(rename = \"b\")] \
3966             #[cfg_attr(feature = \"json\", serde(default))]"
3967                .into(),
3968        )];
3969        let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap();
3970        let parsed: syn::ItemStruct = syn::parse2(quote::quote!(#result struct S;)).unwrap();
3971        let paths: Vec<String> = parsed
3972            .attrs
3973            .iter()
3974            .map(|attr| attr.path().get_ident().unwrap().to_string())
3975            .collect();
3976        assert_eq!(paths, ["doc", "derive", "serde", "cfg_attr"]);
3977    }
3978
3979    #[test]
3980    fn test_matches_proto_prefix_catchall() {
3981        assert!(matches_proto_prefix(".", ".anything.here"));
3982        assert!(matches_proto_prefix(".", "."));
3983    }
3984
3985    #[test]
3986    fn test_matches_proto_prefix_segment_boundary() {
3987        // Segment-aware: ".my.pk" must not match ".my.pkg".
3988        assert!(!matches_proto_prefix(".my.pk", ".my.pkg.Msg"));
3989        // But full-segment prefix match does.
3990        assert!(matches_proto_prefix(".my.pkg", ".my.pkg.Msg"));
3991    }
3992
3993    /// Resolve `fqns` under `global` + `rules` for JSON strictness, in order.
3994    fn resolve_deny_unknown_json(global: bool, rules: &[(&str, bool)], fqns: &[&str]) -> Vec<bool> {
3995        let files = [make_file("t.proto", "test", vec![msg("Outer")], vec![])];
3996        let config = CodeGenConfig {
3997            deny_unknown_json_fields: global,
3998            deny_unknown_json_fields_in: rules
3999                .iter()
4000                .map(|(path, enabled)| ((*path).to_string(), *enabled))
4001                .collect(),
4002            ..CodeGenConfig::default()
4003        };
4004        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
4005        fqns.iter()
4006            .map(|f| ctx.deny_unknown_json_fields(f))
4007            .collect()
4008    }
4009
4010    #[test]
4011    fn deny_unknown_json_fields_defaults_to_lenient() {
4012        assert_eq!(
4013            resolve_deny_unknown_json(false, &[], &["test.Outer"]),
4014            [false]
4015        );
4016    }
4017
4018    #[test]
4019    fn deny_unknown_json_fields_last_matching_rule_wins() {
4020        // A later, more specific rule carves a message back out of a broader
4021        // one, and the dotted and undotted spellings resolve alike.
4022        let config = CodeGenConfig {
4023            deny_unknown_json_fields: false,
4024            deny_unknown_json_fields_in: vec![
4025                (".test".to_string(), true),
4026                (".test.Lenient".to_string(), false),
4027            ],
4028            ..CodeGenConfig::default()
4029        };
4030        let files = [make_file(
4031            "t.proto",
4032            "test",
4033            vec![msg("Strict"), msg("Lenient")],
4034            vec![],
4035        )];
4036        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
4037        assert!(ctx.deny_unknown_json_fields("test.Strict"));
4038        assert!(ctx.deny_unknown_json_fields(".test.Strict"));
4039        assert!(!ctx.deny_unknown_json_fields("test.Lenient"));
4040        assert!(!ctx.deny_unknown_json_fields("test.Lenient.Child"));
4041        assert!(!ctx.deny_unknown_json_fields("other.Msg"));
4042    }
4043
4044    #[test]
4045    fn deny_unknown_json_fields_parent_rule_covers_nested_messages() {
4046        // Segment-aware prefix: nested messages are covered, a sibling whose
4047        // name merely starts with the same characters is not.
4048        let got = resolve_deny_unknown_json(
4049            false,
4050            &[(".test.Outer", true)],
4051            &[
4052                "test.Outer",
4053                "test.Outer.Inner",
4054                "test.Outer.Inner.Deep",
4055                "test.OuterX",
4056                "test.Other",
4057            ],
4058        );
4059        assert_eq!(got, [true, true, true, false, false]);
4060    }
4061
4062    #[test]
4063    fn deny_unknown_json_fields_child_rule_does_not_enable_parent() {
4064        let got = resolve_deny_unknown_json(
4065            false,
4066            &[(".test.Outer.Inner", true)],
4067            &["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"],
4068        );
4069        assert_eq!(got, [false, true, true]);
4070    }
4071
4072    #[test]
4073    fn preserve_unknown_fields_path_override_last_match_wins() {
4074        let files = [make_file(
4075            "t.proto",
4076            "test",
4077            vec![msg("Keep"), msg("Drop"), msg("Nested")],
4078            vec![],
4079        )];
4080        let config = CodeGenConfig {
4081            preserve_unknown_fields: false,
4082            preserve_unknown_fields_in: vec![
4083                (".test".to_string(), true),
4084                (".test.Drop".to_string(), false),
4085            ],
4086            ..CodeGenConfig::default()
4087        };
4088        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
4089        assert!(ctx.preserve_unknown_fields("test.Keep"));
4090        assert!(ctx.preserve_unknown_fields(".test.Keep"));
4091        assert!(!ctx.preserve_unknown_fields("test.Drop"));
4092        // Package prefix `.test` matches nested FQNs; a more specific
4093        // `.test.Drop` rule still wins for Drop's children.
4094        assert!(ctx.preserve_unknown_fields("test.Keep.Nested"));
4095        assert!(!ctx.preserve_unknown_fields("test.Drop.Child"));
4096        assert!(!ctx.preserve_unknown_fields("other.Msg"));
4097    }
4098
4099    /// Build a context over a single empty file and resolve `fqns` under
4100    /// `global` + `rules`, in order.
4101    fn resolve_preserve(global: bool, rules: &[(&str, bool)], fqns: &[&str]) -> Vec<bool> {
4102        let files = [make_file("t.proto", "test", vec![msg("Outer")], vec![])];
4103        let config = CodeGenConfig {
4104            preserve_unknown_fields: global,
4105            preserve_unknown_fields_in: rules
4106                .iter()
4107                .map(|(path, enabled)| ((*path).to_string(), *enabled))
4108                .collect(),
4109            ..CodeGenConfig::default()
4110        };
4111        let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
4112        fqns.iter()
4113            .map(|f| ctx.preserve_unknown_fields(f))
4114            .collect()
4115    }
4116
4117    #[test]
4118    fn preserve_unknown_fields_child_rule_does_not_enable_parent() {
4119        // Enabling the nested type does not enable the enclosing message.
4120        let got = resolve_preserve(
4121            false,
4122            &[(".test.Outer.Inner", true)],
4123            &["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"],
4124        );
4125        assert_eq!(got, [false, true, true]);
4126    }
4127
4128    #[test]
4129    fn preserve_unknown_fields_parent_rule_covers_nested_messages() {
4130        // A rule naming a message is a proto-segment prefix, so it also
4131        // covers every message nested inside it, but not a sibling whose
4132        // name merely starts with the same characters.
4133        let got = resolve_preserve(
4134            false,
4135            &[(".test.Outer", true)],
4136            &[
4137                "test.Outer",
4138                "test.Outer.Inner",
4139                "test.Outer.Inner.Deep",
4140                "test.OuterX",
4141                "test.Other",
4142            ],
4143        );
4144        assert_eq!(got, [true, true, true, false, false]);
4145    }
4146
4147    #[test]
4148    fn preserve_unknown_fields_later_rule_carves_out_nested_message() {
4149        // Outer on, Inner off: expressible through `CodeGenConfig` because a
4150        // later, more specific rule wins over the enclosing one.
4151        let fqns = ["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"];
4152        let got = resolve_preserve(
4153            false,
4154            &[(".test.Outer", true), (".test.Outer.Inner", false)],
4155            &fqns,
4156        );
4157        assert_eq!(got, [true, false, false]);
4158        // Rule order decides: the same rules reversed re-enable Inner.
4159        let got = resolve_preserve(
4160            false,
4161            &[(".test.Outer.Inner", false), (".test.Outer", true)],
4162            &fqns,
4163        );
4164        assert_eq!(got, [true, true, true]);
4165    }
4166
4167    #[test]
4168    fn preserve_unknown_fields_rules_can_disable_under_global_on() {
4169        let got = resolve_preserve(
4170            true,
4171            &[(".test.Drop", false)],
4172            &["test.Keep", "test.Drop", "test.Drop.Child"],
4173        );
4174        assert_eq!(got, [true, false, false]);
4175    }
4176}