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