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