1use 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
14pub const SENTINEL_MOD: &str = "__buffa";
21
22#[derive(Debug, Clone)]
28pub struct SplitPath {
29 pub to_package: String,
37 pub within_package: String,
40 pub is_extern: bool,
43}
44
45pub struct CodeGenContext<'a> {
51 pub files: &'a [FileDescriptorProto],
53 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 pub type_map: HashMap<String, String>,
64 package_of: HashMap<String, String>,
69 enum_closedness: HashMap<String, bool>,
77 enum_first_value: HashMap<String, i32>,
83 deprecated_enum_values: std::cell::OnceCell<HashMap<String, HashSet<String>>>,
88 comment_map: Arc<HashMap<String, String>>,
101 nested_module_names: HashMap<String, String>,
107 unboxed_oneof_variants: Arc<HashSet<String>>,
112 inlined_message_fields: Arc<HashSet<String>>,
118 warnings: std::cell::RefCell<Vec<crate::CodeGenWarning>>,
130 used_json_policy_types: std::cell::RefCell<std::collections::BTreeSet<String>>,
132 table_plan: std::cell::OnceCell<crate::table_plan::TablePlan>,
136 field_renames: HashMap<(String, i32), String>,
142 oneof_keep_verbatim: HashSet<String>,
145 keyword_field_renames: HashMap<(String, i32), String>,
149 keyword_oneof_renames: HashMap<String, String>,
152 imports: std::cell::RefCell<crate::imports::ImportsPhase>,
164}
165
166fn 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
192const RESERVED_MODULE_NAMES: [&str; 4] = ["self", "super", "crate", "arbitrary"];
202
203const PACKAGE_RESERVED_MODULE_NAME: &str = "oneof";
207
208fn 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
229fn last_path_segment(rust_path: &str) -> &str {
231 rust_path.rsplit("::").next().unwrap_or(rust_path)
232}
233
234fn 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 let mut taken: HashSet<String> = occupied.clone();
266 taken.insert(SENTINEL_MOD.to_string());
267 taken.extend(bases.iter().cloned());
268
269 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
290fn 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
301fn 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 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
330fn 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
346pub(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 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 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 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 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 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 for (package, names) in &pkg_message_names {
507 let mut occupied = child_package_segments(package, &all_packages);
508 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub(crate) fn warn(&self, warning: crate::CodeGenWarning) {
827 self.warnings.borrow_mut().push(warning);
828 }
829
830 pub(crate) fn take_warnings(&self) -> Vec<crate::CodeGenWarning> {
836 self.warnings.take()
837 }
838
839 pub(crate) fn truncate_warnings(&self, len: usize) {
844 self.warnings.borrow_mut().truncate(len);
845 }
846
847 pub(crate) fn warnings_len(&self) -> usize {
850 self.warnings.borrow().len()
851 }
852
853 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 pub(crate) fn imports_begin_collecting(&self) {
866 *self.imports.borrow_mut() =
867 crate::imports::ImportsPhase::Collecting(std::collections::BTreeSet::new());
868 }
869
870 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 pub(crate) fn imports_set_resolving(&self, imports: crate::imports::RootImports) {
880 *self.imports.borrow_mut() = crate::imports::ImportsPhase::Resolving(imports);
881 }
882
883 pub(crate) fn imports_reset(&self) {
888 *self.imports.borrow_mut() = crate::imports::ImportsPhase::Off;
889 }
890
891 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 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 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 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 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 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 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 pub fn comment(&self, fqn: &str) -> Option<&str> {
1012 self.comment_map.get(fqn).map(|s| s.as_str())
1013 }
1014
1015 pub fn is_enum_closed(&self, proto_fqn: &str) -> Option<bool> {
1022 self.enum_closedness.get(proto_fqn).copied()
1023 }
1024
1025 pub(crate) fn enum_first_value(&self, proto_fqn: &str) -> Option<i32> {
1028 self.enum_first_value.get(proto_fqn).copied()
1029 }
1030
1031 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 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 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 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 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 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 let common_len = current_parts
1117 .iter()
1118 .zip(&target_parts)
1119 .take_while(|(a, b)| a == b)
1120 .count();
1121
1122 let up_count = (current_parts.len() - common_len) + nesting;
1125
1126 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 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 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 let target_rust_module = if full_path.starts_with("::") || full_path.starts_with("crate::")
1173 {
1174 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn oneof_unboxed(&self, variant_fqn: &str) -> bool {
1644 self.unboxed_oneof_variants.contains(variant_fqn)
1645 }
1646
1647 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 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 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 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 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 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 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#[derive(Clone, Copy)]
1788pub(crate) struct MessageScope<'a> {
1789 pub ctx: &'a CodeGenContext<'a>,
1791 pub current_package: &'a str,
1793 pub proto_fqn: &'a str,
1796 pub features: &'a ResolvedFeatures,
1798 pub nesting: usize,
1802}
1803
1804impl<'a> MessageScope<'a> {
1805 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 pub fn preserve_unknown_fields(&self) -> bool {
1819 self.ctx.preserve_unknown_fields(self.proto_fqn)
1820 }
1821
1822 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1838pub(crate) enum AncillaryKind {
1839 Oneof,
1841 View,
1843 ViewOneof,
1845 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
1860pub(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 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
1926pub(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
1937fn 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
1955pub(crate) fn resolve_extern_prefix(
1966 package: &str,
1967 extern_paths: &[(String, String)],
1968) -> Option<String> {
1969 let dotted = format!(".{}", package);
1970
1971 let mut best: Option<(&str, &str, usize)> = None;
1974
1975 for (proto_prefix, rust_prefix) in extern_paths {
1976 if dotted == *proto_prefix {
1977 return Some(rust_prefix.clone());
1979 }
1980 if let Some(rest) = dotted.strip_prefix(proto_prefix.as_str()) {
1981 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
2002pub(crate) fn resolve_extern_type(fqn: &str, extern_paths: &[(String, String)]) -> Option<String> {
2022 if let Some((_, rust)) = extern_paths.iter().find(|(proto, _)| proto == fqn) {
2024 return Some(rust.clone());
2025 }
2026
2027 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 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 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
2063fn 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
2073fn 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 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#[derive(Clone, Copy)]
2121struct NestedRegistrationCtx<'a> {
2122 package: &'a str,
2123 extern_paths: &'a [(String, String)],
2124 type_name_prefix: &'a str,
2125}
2126
2127fn 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 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 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 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
2258fn 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
2295fn 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
2346fn 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
2358fn 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
2381pub(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
2392pub(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
2404pub(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 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 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 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 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 let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof", "oof_"]));
2488 assert_eq!(out, vec!["oof__".to_string(), "oof___".to_string()]);
2489 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 let ch = set(&["oof", "oof_"]);
2499 let fwd = deconflict_modules(&names(&["Oof", "Oof_"]), &ch);
2500 let rev = deconflict_modules(&names(&["Oof_", "Oof"]), &ch);
2501 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 let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof"]));
2511 assert_eq!(out, vec!["oof__".to_string(), "oof_".to_string()]);
2513 }
2514
2515 #[test]
2516 fn deconflict_avoids_type_names_and_reserved_names() {
2517 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 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 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 assert_eq!(module("item", "::ext::Pbitem"), "item");
2555 assert_eq!(module("Crate", "::ext::Crate"), "crate_");
2556 assert_eq!(module("crate", "::ext::crate_"), "crate__");
2557 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 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 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 #[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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 assert_eq!(
3315 ctx.rust_type_relative(".a.b.Msg1", "a.bc", 0),
3316 Some("super::b::Msg1".into())
3317 );
3318 assert_eq!(
3320 ctx.rust_type_relative(".a.bc.Msg2", "a.b", 0),
3321 Some("super::bc::Msg2".into())
3322 );
3323 }
3324
3325 #[test]
3328 fn test_relative_cross_package_nesting_1() {
3329 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 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 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 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 assert_eq!(
3366 ctx.rust_type_relative(".pkg.Foo", "pkg", 0),
3367 Some("Foo".into())
3368 );
3369 assert_eq!(
3371 ctx.rust_type_relative(".pkg.Foo", "pkg", 1),
3372 Some("super::Foo".into())
3373 );
3374 assert_eq!(
3376 ctx.rust_type_relative(".pkg.Foo", "pkg", 2),
3377 Some("super::super::Foo".into())
3378 );
3379 }
3380
3381 #[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 assert_eq!(
3391 resolve_file_extern("google/protobuf/descriptor.proto", &mappings),
3392 Some("::buffa_descriptor::generated::descriptor"),
3393 );
3394 assert_eq!(
3397 resolve_file_extern("google/protobuf/timestamp.proto", &mappings),
3398 None,
3399 );
3400 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 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 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 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 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 let result = resolve_extern_prefix("google.type", &[(".".into(), "crate::proto".into())]);
3493 assert_eq!(result, Some("crate::proto::google::type".into()));
3494 }
3495
3496 #[test]
3499 fn test_resolve_extern_type_exact_match() {
3500 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 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 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 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 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 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 #[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 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 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 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 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 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 assert_eq!(
3782 ctx.rust_type(".my.common.SharedMsg"),
3783 Some("::common_protos::SharedMsg")
3784 );
3785 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 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 assert_eq!(
3812 ctx.rust_type_relative(".my.common.SharedMsg", "my.service", 0),
3813 Some("::common_protos::SharedMsg".into())
3814 );
3815 }
3816
3817 #[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 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 assert_eq!(ctx.is_enum_closed(".p.E"), Some(false));
3837 }
3838
3839 #[test]
3840 fn test_is_enum_closed_per_enum_override() {
3841 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 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 assert_eq!(ctx.is_enum_closed(".other.Unknown"), None);
3880 }
3881
3882 #[test]
3883 fn test_for_generate_auto_injects_wkt_mapping() {
3884 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 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 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 assert_eq!(
3930 ctx.rust_type(".google.protobuf.Timestamp"),
3931 Some("google::protobuf::Timestamp")
3932 );
3933 }
3934
3935 #[test]
3938 fn test_matching_attributes_catchall() {
3939 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 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 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 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 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 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 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 assert!(!matches_proto_prefix(".my.pk", ".my.pkg.Msg"));
4086 assert!(matches_proto_prefix(".my.pkg", ".my.pkg.Msg"));
4088 }
4089
4090 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 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 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 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 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 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 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 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 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}