use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::features::{self, ResolvedFeatures};
use crate::generated::descriptor::field_descriptor_proto::Type;
use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
use crate::oneof::to_snake_case;
use crate::CodeGenConfig;
pub const SENTINEL_MOD: &str = "__buffa";
#[derive(Debug, Clone)]
pub struct SplitPath {
pub to_package: String,
pub within_package: String,
pub is_extern: bool,
}
pub struct CodeGenContext<'a> {
pub files: &'a [FileDescriptorProto],
pub config: &'a CodeGenConfig,
denied_view_json: std::cell::OnceCell<HashSet<String>>,
guarded_reflection_messages: std::cell::OnceCell<HashSet<String>>,
pub type_map: HashMap<String, String>,
package_of: HashMap<String, String>,
enum_closedness: HashMap<String, bool>,
enum_first_value: HashMap<String, i32>,
deprecated_enum_values: std::cell::OnceCell<HashMap<String, HashSet<String>>>,
comment_map: Arc<HashMap<String, String>>,
nested_module_names: HashMap<String, String>,
unboxed_oneof_variants: Arc<HashSet<String>>,
inlined_message_fields: Arc<HashSet<String>>,
warnings: std::cell::RefCell<Vec<crate::CodeGenWarning>>,
table_plan: std::cell::OnceCell<crate::table_plan::TablePlan>,
field_renames: HashMap<(String, i32), String>,
oneof_keep_verbatim: HashSet<String>,
keyword_field_renames: HashMap<(String, i32), String>,
keyword_oneof_renames: HashMap<String, String>,
imports: std::cell::RefCell<crate::imports::ImportsPhase>,
}
fn child_package_segments(package: &str, all_packages: &HashSet<String>) -> HashSet<String> {
let prefix = if package.is_empty() {
String::new()
} else {
format!("{package}.")
};
all_packages
.iter()
.filter_map(|p| {
let rest = if package.is_empty() {
Some(p.as_str())
} else {
p.strip_prefix(&prefix)
};
rest.filter(|r| !r.is_empty())
.map(|r| r.split('.').next().unwrap_or(r).to_string())
})
.collect()
}
const RESERVED_MODULE_NAMES: [&str; 4] = ["self", "super", "crate", "arbitrary"];
const PACKAGE_RESERVED_MODULE_NAME: &str = "oneof";
fn extern_override_module(name: &str, rust_path: &str, package_level: bool) -> String {
let type_name = last_path_segment(rust_path);
let mut module = to_snake_case(name);
if RESERVED_MODULE_NAMES.contains(&module.as_str())
|| (package_level && module == PACKAGE_RESERVED_MODULE_NAME)
|| module == type_name
{
module.push('_');
while module == type_name {
module.push('_');
}
}
module
}
fn last_path_segment(rust_path: &str) -> &str {
rust_path.rsplit("::").next().unwrap_or(rust_path)
}
fn deconflict_modules(message_names: &[String], occupied: &HashSet<String>) -> Vec<String> {
let bases: Vec<String> = message_names.iter().map(|n| to_snake_case(n)).collect();
let is_occupied =
|base: &String| RESERVED_MODULE_NAMES.contains(&base.as_str()) || occupied.contains(base);
if !bases.iter().any(is_occupied) {
return bases;
}
let mut taken: HashSet<String> = occupied.clone();
taken.insert(SENTINEL_MOD.to_string());
taken.extend(bases.iter().cloned());
let mut out = bases.clone();
let mut order: Vec<usize> = (0..bases.len()).collect();
order.sort_by(|&a, &b| (&bases[a], &message_names[a]).cmp(&(&bases[b], &message_names[b])));
for i in order {
if !is_occupied(&bases[i]) {
continue;
}
let mut candidate = format!("{}_", bases[i]);
while taken.contains(&candidate) {
candidate.push('_');
}
taken.insert(candidate.clone());
out[i] = candidate;
}
out
}
fn keyword_rename_note(kind: &str, resolved: &str) -> String {
let stem = resolved.trim_end_matches('_');
format!(
" Note: `{stem}_`, the usual Rust name of this {kind}, is the name of another \
member of this message or of a message that declares the same {kind}, so this \
{kind} is `{resolved}`."
)
}
fn parse_outer_attribute_string(attr_str: &str) -> syn::Result<proc_macro2::TokenStream> {
use syn::parse::Parser as _;
let parser = |input: syn::parse::ParseStream<'_>| {
if input.peek(syn::Token![#]) && input.peek2(syn::Token![!]) {
return Err(input.error("an inner attribute `#![...]` is not accepted; write `#[...]`"));
}
let attrs = input.call(syn::Attribute::parse_outer)?;
if !input.is_empty() {
return Err(input.error("expected an outer attribute of the form `#[...]`"));
}
if attrs.is_empty() {
return Err(syn::Error::new(
proc_macro2::Span::call_site(),
"expected at least one `#[...]` attribute",
));
}
Ok(quote::quote!(#(#attrs)*))
};
parser.parse_str(attr_str)
}
fn parse_custom_attribute(
path: &str,
attr_str: &str,
) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
parse_outer_attribute_string(attr_str).map_err(|err| {
crate::CodeGenError::InvalidCustomAttribute {
path: path.to_string(),
attribute: attr_str.to_string(),
detail: err.to_string(),
}
})
}
pub(crate) fn validate_custom_attributes(
config: &crate::CodeGenConfig,
) -> Result<(), crate::CodeGenError> {
[
&config.type_attributes,
&config.field_attributes,
&config.message_attributes,
&config.enum_attributes,
&config.oneof_attributes,
&config.oneof_struct_field_attributes,
]
.into_iter()
.flatten()
.try_for_each(|(path, attr_str)| parse_custom_attribute(path, attr_str).map(drop))
}
impl<'a> CodeGenContext<'a> {
pub fn new(
files: &'a [FileDescriptorProto],
config: &'a CodeGenConfig,
effective_extern_paths: &[(String, String)],
) -> Self {
Self::with_extern_resolution(files, config, effective_extern_paths, &[], None)
}
pub(crate) fn with_extern_resolution(
files: &'a [FileDescriptorProto],
config: &'a CodeGenConfig,
effective_extern_paths: &[(String, String)],
file_extern_paths: &[(String, String)],
generated_files: Option<&HashSet<String>>,
) -> Self {
let mut type_map = HashMap::new();
let mut package_of = HashMap::new();
let mut enum_closedness = HashMap::new();
let mut nested_module_names = HashMap::new();
let shared = match &config.shared_corpus_context {
Some(shared) => {
debug_assert!(
shared.check(files, config).is_ok(),
"shared_corpus_context does not match this call's files or rules"
);
shared.clone()
}
None => crate::SharedCorpusContext::new(files, config),
};
let unboxed_oneof_variants = Arc::clone(shared.unboxed_oneof_variants());
let inlined_message_fields = Arc::clone(shared.inlined_message_fields());
let comment_map = Arc::clone(shared.comment_map());
let mut all_packages: HashSet<String> = HashSet::new();
let mut pkg_message_names: HashMap<String, Vec<String>> = HashMap::new();
let mut pkg_type_names: HashMap<String, HashSet<String>> = HashMap::new();
for file in files {
let package = file.package.as_deref().unwrap_or("");
all_packages.insert(package.to_string());
let file_root = file
.name
.as_deref()
.and_then(|n| resolve_file_extern(n, file_extern_paths));
let local_module = package.replace('.', "::");
let messages = file.message_type.iter().map(|m| (m.name.as_ref(), true));
let enums = file.enum_type.iter().map(|e| (e.name.as_ref(), false));
for (name, is_message) in messages.chain(enums) {
let Some(name) = name else { continue };
let fqn = if package.is_empty() {
format!(".{name}")
} else {
format!(".{package}.{name}")
};
if effective_extern_paths
.iter()
.any(|(proto, _)| proto == &fqn)
{
continue;
}
let (rust_path, _) = resolve_type_path(
&fqn,
name,
file_root,
&local_module,
effective_extern_paths,
&config.type_name_prefix,
);
pkg_type_names
.entry(package.to_string())
.or_default()
.insert(last_path_segment(&rust_path).to_string());
if is_message {
pkg_message_names
.entry(package.to_string())
.or_default()
.push(name.clone());
}
}
}
for (package, names) in &pkg_message_names {
let mut occupied = child_package_segments(package, &all_packages);
let escaped: Vec<String> = ["self", "super", "crate"]
.iter()
.filter(|name| occupied.contains(**name))
.map(|name| format!("{name}_"))
.collect();
occupied.extend(escaped);
occupied.insert(PACKAGE_RESERVED_MODULE_NAME.to_string());
if let Some(type_names) = pkg_type_names.get(package) {
occupied.extend(type_names.iter().cloned());
}
let modules = deconflict_modules(names, &occupied);
for (name, module) in names.iter().zip(modules) {
if module == to_snake_case(name) {
continue;
}
let fqn = if package.is_empty() {
format!(".{name}")
} else {
format!(".{package}.{name}")
};
nested_module_names.insert(fqn, module);
}
}
for file in files {
let package = file.package.as_deref().unwrap_or("");
let file_features = features::for_file(file);
let proto_prefix = if package.is_empty() {
String::from(".")
} else {
format!(".{}.", package)
};
let file_root = file
.name
.as_deref()
.and_then(|n| resolve_file_extern(n, file_extern_paths));
let local_module = package.replace('.', "::");
for msg in &file.message_type {
if let Some(name) = &msg.name {
let fqn = format!("{}{}", proto_prefix, name);
let (rust_path, is_extern) = resolve_type_path(
&fqn,
name,
file_root,
&local_module,
effective_extern_paths,
&config.type_name_prefix,
);
let is_exact_override = effective_extern_paths
.iter()
.any(|(proto, _)| proto == &fqn);
let module = if is_exact_override {
extern_override_module(name, &rust_path, true)
} else {
nested_module_names
.get(&fqn)
.cloned()
.unwrap_or_else(|| to_snake_case(name))
};
let parent_mod = if is_extern {
match rust_path.rsplit_once("::") {
Some((parent, _)) => format!("{parent}::{module}"),
None => module,
}
} else {
join_mod(&local_module, &module)
};
type_map.insert(fqn.clone(), rust_path);
package_of.insert(fqn.clone(), package.to_string());
register_nested_types(
&mut type_map,
&mut package_of,
&mut nested_module_names,
NestedRegistrationCtx {
package,
extern_paths: effective_extern_paths,
type_name_prefix: &config.type_name_prefix,
},
&fqn,
&parent_mod,
msg,
);
register_nested_enum_closedness(
&mut enum_closedness,
&fqn,
&file_features,
msg,
);
}
}
for enum_type in &file.enum_type {
if let Some(name) = &enum_type.name {
let fqn = format!("{}{}", proto_prefix, name);
let (rust_path, _) = resolve_type_path(
&fqn,
name,
file_root,
&local_module,
effective_extern_paths,
&config.type_name_prefix,
);
type_map.insert(fqn.clone(), rust_path);
package_of.insert(fqn.clone(), package.to_string());
register_enum_closedness(&mut enum_closedness, &fqn, &file_features, enum_type);
}
}
}
let (field_renames, oneof_keep_verbatim, mut plan_warnings) =
if config.idiomatic_field_names {
let plan = crate::field_names::plan_field_names(files);
(plan.field_renames, plan.oneof_keep_verbatim, plan.warnings)
} else {
(HashMap::new(), HashSet::new(), Vec::new())
};
let keyword_plan = crate::field_names::plan_keyword_escapes(
files,
config.idiomatic_field_names,
&field_renames,
&oneof_keep_verbatim,
generated_files,
);
plan_warnings.extend(keyword_plan.warnings);
Self {
files,
config,
denied_view_json: std::cell::OnceCell::new(),
guarded_reflection_messages: std::cell::OnceCell::new(),
type_map,
package_of,
enum_closedness,
enum_first_value: if config.has_enum_type_overrides() {
collect_enum_first_values(files)
} else {
HashMap::new()
},
deprecated_enum_values: std::cell::OnceCell::new(),
comment_map,
nested_module_names,
unboxed_oneof_variants,
inlined_message_fields,
table_plan: std::cell::OnceCell::new(),
field_renames,
oneof_keep_verbatim,
keyword_field_renames: keyword_plan.field_renames,
keyword_oneof_renames: keyword_plan.oneof_renames,
warnings: std::cell::RefCell::new(plan_warnings),
imports: std::cell::RefCell::new(crate::imports::ImportsPhase::Off),
}
}
pub(crate) fn field_rust_name<'n>(&'n self, name: &'n str, number: i32) -> Cow<'n, str> {
if !self.keyword_field_renames.is_empty() {
if let Some(renamed) = self.keyword_field_renames.get(&(name.to_string(), number)) {
return Cow::Borrowed(renamed.as_str());
}
}
crate::field_names::planned_field_name(
self.config.idiomatic_field_names,
&self.field_renames,
name,
number,
)
}
pub(crate) fn field_ident(&self, name: &str, number: i32) -> proc_macro2::Ident {
crate::idents::make_field_ident(&self.field_rust_name(name, number))
}
pub(crate) fn oneof_rust_name<'n>(&'n self, name: &'n str) -> Cow<'n, str> {
if !self.keyword_oneof_renames.is_empty() {
if let Some(renamed) = self.keyword_oneof_renames.get(name) {
return Cow::Borrowed(renamed.as_str());
}
}
crate::field_names::planned_oneof_name(
self.config.idiomatic_field_names,
&self.oneof_keep_verbatim,
name,
)
}
pub(crate) fn oneof_ident(&self, name: &str) -> proc_macro2::Ident {
crate::idents::make_field_ident(&self.oneof_rust_name(name))
}
pub(crate) fn field_rename_note(&self, name: &str, number: i32) -> Option<String> {
if !self.keyword_field_renames.is_empty() {
if let Some(resolved) = self.keyword_field_renames.get(&(name.to_string(), number)) {
return Some(keyword_rename_note("field", resolved));
}
}
if !self.config.idiomatic_field_names || self.field_renames.is_empty() {
return None;
}
let resolved = self.field_renames.get(&(name.to_string(), number))?;
Some(format!(
" Note: the snake_case conversion of `{name}` collides with another \
member of this message; the Rust name was adjusted to `{resolved}` \
(`_f<n>` suffixes carry the field number)."
))
}
pub(crate) fn oneof_rename_note(&self, name: &str) -> Option<String> {
let resolved = self.keyword_oneof_renames.get(name)?;
Some(keyword_rename_note("oneof", resolved))
}
pub(crate) fn message_non_snake_attr(&self, msg: &DescriptorProto) -> proc_macro2::TokenStream {
let non_snake = |s: &str| s.contains(|c: char| c.is_ascii_uppercase());
let mut real_oneofs: HashSet<i32> = HashSet::new();
let mut found = false;
for field in &msg.field {
let Some(name) = field.name.as_deref() else {
continue;
};
if field.oneof_index.is_some() && !field.proto3_optional.unwrap_or(false) {
if let Some(idx) = field.oneof_index {
real_oneofs.insert(idx);
}
continue;
}
if non_snake(&self.field_rust_name(name, field.number.unwrap_or(0))) {
found = true;
break;
}
}
if !found {
for (idx, oneof) in msg.oneof_decl.iter().enumerate() {
let Some(name) = oneof.name.as_deref() else {
continue;
};
if !real_oneofs.contains(&i32::try_from(idx).unwrap_or(i32::MAX)) {
continue;
}
if non_snake(&self.oneof_rust_name(name)) {
found = true;
break;
}
}
}
if found {
quote::quote! { #[allow(non_snake_case)] }
} else {
proc_macro2::TokenStream::new()
}
}
pub(crate) fn warn(&self, warning: crate::CodeGenWarning) {
self.warnings.borrow_mut().push(warning);
}
pub(crate) fn take_warnings(&self) -> Vec<crate::CodeGenWarning> {
self.warnings.take()
}
pub(crate) fn truncate_warnings(&self, len: usize) {
self.warnings.borrow_mut().truncate(len);
}
pub(crate) fn warnings_len(&self) -> usize {
self.warnings.borrow().len()
}
pub(crate) fn package_of(&self, proto_fqn: &str) -> Option<&str> {
self.package_of.get(proto_fqn).map(String::as_str)
}
pub(crate) fn imports_begin_collecting(&self) {
*self.imports.borrow_mut() =
crate::imports::ImportsPhase::Collecting(std::collections::BTreeSet::new());
}
pub(crate) fn imports_take_collected(&self) -> std::collections::BTreeSet<String> {
match self.imports.replace(crate::imports::ImportsPhase::Off) {
crate::imports::ImportsPhase::Collecting(set) => set,
_ => std::collections::BTreeSet::new(),
}
}
pub(crate) fn imports_set_resolving(&self, imports: crate::imports::RootImports) {
*self.imports.borrow_mut() = crate::imports::ImportsPhase::Resolving(imports);
}
pub(crate) fn imports_reset(&self) {
*self.imports.borrow_mut() = crate::imports::ImportsPhase::Off;
}
pub(crate) fn imports_use_block(&self) -> proc_macro2::TokenStream {
match &*self.imports.borrow() {
crate::imports::ImportsPhase::Resolving(imports) => imports.use_items(),
_ => proc_macro2::TokenStream::new(),
}
}
fn root_path(&self, path: String, nesting: usize) -> String {
if nesting != 0 {
return path;
}
match &mut *self.imports.borrow_mut() {
crate::imports::ImportsPhase::Off => path,
crate::imports::ImportsPhase::Collecting(set) => {
if crate::imports::shortenable(&path) {
set.insert(path.clone());
}
path
}
crate::imports::ImportsPhase::Resolving(imports) => match imports.resolve(&path) {
Some(short) => short.to_string(),
None => path,
},
}
}
pub(crate) fn root_runtime_path(
&self,
canonical: &str,
nesting: usize,
) -> proc_macro2::TokenStream {
crate::idents::rust_path_to_tokens(&self.root_path(canonical.to_string(), nesting))
}
pub fn nested_module_name(&self, package: &str, name: &str) -> String {
if package.is_empty() {
self.message_module_name(name)
} else {
self.message_module_name(&format!("{package}.{name}"))
}
}
pub(crate) fn message_module_name(&self, proto_fqn: &str) -> String {
self.nested_module_names
.get(&format!(".{proto_fqn}"))
.cloned()
.unwrap_or_else(|| to_snake_case(proto_fqn.rsplit('.').next().unwrap_or(proto_fqn)))
}
pub fn for_generate(
files: &'a [FileDescriptorProto],
files_to_generate: &[String],
config: &'a CodeGenConfig,
) -> Self {
let paths = crate::effective_extern_paths(files, files_to_generate, config);
let file_paths = crate::effective_file_extern_paths(files_to_generate, config);
let generated_files: HashSet<String> = files_to_generate.iter().cloned().collect();
Self::with_extern_resolution(files, config, &paths, &file_paths, Some(&generated_files))
}
pub fn rust_type(&self, proto_fqn: &str) -> Option<&str> {
self.type_map.get(proto_fqn).map(|s| s.as_str())
}
pub fn comment(&self, fqn: &str) -> Option<&str> {
self.comment_map.get(fqn).map(|s| s.as_str())
}
pub fn is_enum_closed(&self, proto_fqn: &str) -> Option<bool> {
self.enum_closedness.get(proto_fqn).copied()
}
pub(crate) fn enum_first_value(&self, proto_fqn: &str) -> Option<i32> {
self.enum_first_value.get(proto_fqn).copied()
}
pub(crate) fn enum_value_is_deprecated(&self, proto_fqn: &str, value_name: &str) -> bool {
self.deprecated_enum_values
.get_or_init(|| collect_deprecated_enum_values(self.files))
.get(proto_fqn)
.is_some_and(|names| names.contains(value_name))
}
pub fn rust_type_relative(
&self,
proto_fqn: &str,
current_package: &str,
nesting: usize,
) -> Option<String> {
let full_path = self.type_map.get(proto_fqn)?;
if full_path.starts_with("::") || full_path.starts_with("crate::") {
return Some(self.root_path(full_path.clone(), nesting));
}
let target_package = self
.package_of
.get(proto_fqn)
.map(|s| s.as_str())
.unwrap_or("");
let target_rust_module = target_package.replace('.', "::");
let type_suffix = if target_rust_module.is_empty() {
full_path.as_str()
} else {
full_path
.strip_prefix(&format!("{}::", target_rust_module))
.unwrap_or(full_path)
};
if current_package == target_package {
if nesting == 0 {
return Some(type_suffix.to_string());
}
let supers = (0..nesting).map(|_| "super").collect::<Vec<_>>().join("::");
return Some(format!("{}::{}", supers, type_suffix));
}
let current_parts: Vec<&str> = if current_package.is_empty() {
vec![]
} else {
current_package.split('.').collect()
};
let target_parts: Vec<&str> = if target_package.is_empty() {
vec![]
} else {
target_package.split('.').collect()
};
let common_len = current_parts
.iter()
.zip(&target_parts)
.take_while(|(a, b)| a == b)
.count();
let up_count = (current_parts.len() - common_len) + nesting;
let down_parts = &target_parts[common_len..];
let mut segments: Vec<&str> = vec!["super"; up_count];
segments.extend_from_slice(down_parts);
let mut result = segments.join("::");
if !result.is_empty() {
result.push_str("::");
}
result.push_str(type_suffix);
Some(self.root_path(result, nesting))
}
pub fn rust_type_relative_split(
&self,
proto_fqn: &str,
current_package: &str,
nesting: usize,
) -> Option<SplitPath> {
let full_path = self.type_map.get(proto_fqn)?;
let target_package = self
.package_of
.get(proto_fqn)
.map(|s| s.as_str())
.unwrap_or("");
let target_rust_module = if full_path.starts_with("::") || full_path.starts_with("crate::")
{
let fqn_no_dot = proto_fqn.strip_prefix('.').unwrap_or(proto_fqn);
let within_proto = if target_package.is_empty() {
fqn_no_dot
} else {
fqn_no_dot
.strip_prefix(target_package)
.and_then(|s| s.strip_prefix('.'))
.unwrap_or(fqn_no_dot)
};
let within_segs = within_proto.split('.').count();
let full_segs: Vec<&str> = full_path.split("::").collect();
let cut = full_segs.len().saturating_sub(within_segs);
full_segs[..cut].join("::")
} else {
target_package.replace('.', "::")
};
let type_suffix = if target_rust_module.is_empty() {
full_path.as_str()
} else {
full_path
.strip_prefix(&format!("{}::", target_rust_module))
.unwrap_or(full_path)
};
if full_path.starts_with("::") || full_path.starts_with("crate::") {
return Some(SplitPath {
to_package: target_rust_module,
within_package: type_suffix.to_string(),
is_extern: true,
});
}
if current_package == target_package {
let to_package = if nesting == 0 {
String::new()
} else {
(0..nesting).map(|_| "super").collect::<Vec<_>>().join("::")
};
return Some(SplitPath {
to_package,
within_package: type_suffix.to_string(),
is_extern: false,
});
}
let current_parts: Vec<&str> = if current_package.is_empty() {
vec![]
} else {
current_package.split('.').collect()
};
let target_parts: Vec<&str> = if target_package.is_empty() {
vec![]
} else {
target_package.split('.').collect()
};
let common_len = current_parts
.iter()
.zip(&target_parts)
.take_while(|(a, b)| a == b)
.count();
let up_count = (current_parts.len() - common_len) + nesting;
let down_parts = &target_parts[common_len..];
let mut segments: Vec<&str> = vec!["super"; up_count];
segments.extend_from_slice(down_parts);
Some(SplitPath {
to_package: segments.join("::"),
within_package: type_suffix.to_string(),
is_extern: false,
})
}
pub(crate) fn matching_attributes(
attrs: &[(String, String)],
fqn: &str,
) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
if attrs.is_empty() {
return Ok(proc_macro2::TokenStream::new());
}
let fqn_dotted = format!(".{fqn}");
let mut tokens = proc_macro2::TokenStream::new();
for (prefix, attr_str) in attrs {
if matches_proto_prefix(prefix, &fqn_dotted) {
tokens.extend(parse_custom_attribute(prefix, attr_str)?);
}
}
Ok(tokens)
}
pub fn bytes_repr(&self, field_fqn: &str) -> crate::BytesRepr {
self.config
.bytes_fields
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
.map_or(crate::BytesRepr::default(), |(_, repr)| repr.clone())
}
pub(crate) fn zeroizes_message(&self, msg_fqn: &str) -> bool {
let dotted = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
self.config.generate_zeroize
|| self
.config
.zeroize_messages
.iter()
.any(|prefix| matches_proto_prefix(prefix, &dotted))
}
fn containing_messages(&self, selected: impl Fn(&str) -> bool) -> HashSet<String> {
fn walk(
messages: &[DescriptorProto],
prefix: &str,
edges: &mut Vec<(String, Vec<String>)>,
) {
for message in messages {
let Some(name) = message.name.as_deref() else {
continue;
};
let name = format!("{prefix}.{name}");
let children = message
.field
.iter()
.filter(|field| {
matches!(field.r#type, Some(Type::TYPE_MESSAGE | Type::TYPE_GROUP))
})
.filter_map(|field| field.type_name.clone())
.collect();
edges.push((name.clone(), children));
walk(&message.nested_type, &name, edges);
}
}
let mut edges = Vec::new();
for file in self.files {
let package = file.package.as_deref().unwrap_or_default();
let prefix = if package.is_empty() {
String::new()
} else {
format!(".{package}")
};
walk(&file.message_type, &prefix, &mut edges);
}
let mut denied = HashSet::new();
let mut pending = Vec::new();
let mut parents: HashMap<String, Vec<String>> = HashMap::new();
for (name, children) in edges {
for child in children {
parents.entry(child).or_default().push(name.clone());
}
if selected(&name) {
denied.insert(name.clone());
pending.push(name);
}
}
while let Some(child) = pending.pop() {
if let Some(containers) = parents.get(&child) {
for parent in containers {
if denied.insert(parent.clone()) {
pending.push(parent.clone());
}
}
}
}
denied
}
pub(crate) fn denies_view_json(&self, msg_fqn: &str) -> bool {
if self.config.deny_view_json.is_empty() {
return false;
}
let denied = self.denied_view_json.get_or_init(|| {
self.containing_messages(|name| {
self.config
.deny_view_json
.iter()
.any(|rule| matches_proto_prefix(rule, name))
})
});
let name = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
denied.contains(name.as_ref())
}
pub(crate) fn contains_guarded_reflection(&self, msg_fqn: &str) -> bool {
if !self.config.generate_reflection
|| (!self.config.generate_zeroize && self.config.zeroize_messages.is_empty())
{
return false;
}
let guarded = self
.guarded_reflection_messages
.get_or_init(|| self.containing_messages(|name| self.zeroizes_message(name)));
let name = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
guarded.contains(name.as_ref())
}
pub fn preserve_unknown_fields(&self, msg_fqn: &str) -> bool {
let rules = &self.config.preserve_unknown_fields_in;
if rules.is_empty() {
return self.config.preserve_unknown_fields;
}
let dotted = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
rules
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
.map_or(self.config.preserve_unknown_fields, |(_, enabled)| *enabled)
}
pub(crate) fn codec_strategy_rule(
&self,
msg_fqn: &str,
) -> Option<&'a (String, crate::CodecStrategy)> {
let dotted = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
self.config
.codec_strategy_in
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
}
pub(crate) fn codec_strategy(&self, msg_fqn: &str) -> crate::CodecStrategy {
self.codec_strategy_rule(msg_fqn)
.map_or(self.config.codec_strategy, |(_, strategy)| *strategy)
}
pub(crate) fn table_codec_requested(&self) -> bool {
self.config.codec_strategy == crate::CodecStrategy::Table
|| self
.config
.codec_strategy_in
.iter()
.any(|(_, s)| *s == crate::CodecStrategy::Table)
}
pub(crate) fn plan_table_codec(
&self,
files: &[crate::generated::descriptor::FileDescriptorProto],
files_to_generate: &[String],
) -> Result<(), crate::CodeGenError> {
let (plan, warnings) = crate::table_plan::plan(self, files, files_to_generate)?;
for w in warnings {
self.warn(w);
}
let planned = self.table_plan.set(plan);
debug_assert!(planned.is_ok(), "the table codec is planned once per run");
Ok(())
}
pub(crate) fn uses_table_codec(&self, msg_fqn: &str) -> bool {
let Some(plan) = self.table_plan.get() else {
return false;
};
if msg_fqn.starts_with('.') {
plan.contains(msg_fqn)
} else {
plan.contains(&format!(".{msg_fqn}"))
}
}
pub fn deny_unknown_json_fields(&self, msg_fqn: &str) -> bool {
let rules = &self.config.deny_unknown_json_fields_in;
if rules.is_empty() {
return self.config.deny_unknown_json_fields;
}
let dotted = if msg_fqn.starts_with('.') {
Cow::Borrowed(msg_fqn)
} else {
Cow::Owned(format!(".{msg_fqn}"))
};
rules
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, &dotted))
.map_or(self.config.deny_unknown_json_fields, |(_, enabled)| {
*enabled
})
}
pub fn skip_debug(&self, message_fqn: &str) -> bool {
if self.config.skip_debug.is_empty() {
return false;
}
let dotted = if message_fqn.starts_with('.') {
Cow::Borrowed(message_fqn)
} else {
Cow::Owned(format!(".{message_fqn}"))
};
self.config
.skip_debug
.iter()
.any(|prefix| matches_proto_prefix(prefix, &dotted))
}
pub fn skip_debug_enum(&self, enum_fqn: &str) -> bool {
let name = enum_fqn.strip_prefix('.').unwrap_or(enum_fqn);
self.config
.skip_debug
.iter()
.any(|rule| rule.strip_prefix('.') == Some(name))
}
pub fn oneof_unboxed(&self, variant_fqn: &str) -> bool {
self.unboxed_oneof_variants.contains(variant_fqn)
}
pub(crate) fn is_json_policy_type(&self, rust_type: &str) -> bool {
if !self.config.generate_json || self.config.json_policy_types.is_empty() {
return false;
}
let key = rust_type_key(rust_type);
self.config
.json_policy_types
.iter()
.any(|listed| rust_type_key(listed) == key)
}
pub fn string_repr(&self, field_fqn: &str) -> crate::StringRepr {
self.config
.string_fields
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
.map_or(crate::StringRepr::default(), |(_, repr)| repr.clone())
}
pub fn map_repr(&self, field_fqn: &str) -> crate::MapRepr {
self.config
.map_fields
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
.map_or_else(
|| {
if field_fqn
.rsplit_once('.')
.is_some_and(|(message, _)| self.zeroizes_message(message))
{
crate::MapRepr::Custom("::buffa::sensitive::Map".into())
} else {
crate::MapRepr::default()
}
},
|(_, repr)| repr.clone(),
)
}
pub fn pointer_repr(&self, field_fqn: &str) -> crate::PointerRepr {
let raw = self
.config
.pointer_fields
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
.map_or(crate::PointerRepr::default(), |(_, repr)| repr.clone());
if raw == crate::PointerRepr::Inline && !self.inlined_message_fields.contains(field_fqn) {
crate::PointerRepr::Box
} else {
raw
}
}
pub fn repeated_repr(&self, field_fqn: &str) -> crate::RepeatedRepr {
self.config
.repeated_fields
.iter()
.rev()
.find(|(prefix, _)| matches_proto_prefix(prefix, field_fqn))
.map_or_else(
|| {
if field_fqn
.rsplit_once('.')
.is_some_and(|(message, _)| self.zeroizes_message(message))
{
crate::RepeatedRepr::Custom("::buffa::sensitive::List<*>".into())
} else {
crate::RepeatedRepr::default()
}
},
|(_, repr)| repr.clone(),
)
}
}
#[derive(Clone, Copy)]
pub(crate) struct MessageScope<'a> {
pub ctx: &'a CodeGenContext<'a>,
pub current_package: &'a str,
pub proto_fqn: &'a str,
pub features: &'a ResolvedFeatures,
pub nesting: usize,
}
impl<'a> MessageScope<'a> {
pub fn nested(&self, proto_fqn: &'a str, features: &'a ResolvedFeatures) -> MessageScope<'a> {
MessageScope {
ctx: self.ctx,
current_package: self.current_package,
proto_fqn,
features,
nesting: self.nesting + 1,
}
}
pub fn preserve_unknown_fields(&self) -> bool {
self.ctx.preserve_unknown_fields(self.proto_fqn)
}
pub fn deny_unknown_json_fields(&self) -> bool {
self.ctx.config.generate_json && self.ctx.deny_unknown_json_fields(self.proto_fqn)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum AncillaryKind {
Oneof,
View,
ViewOneof,
LazyView,
}
impl AncillaryKind {
fn path_segments(self) -> &'static [&'static str] {
match self {
Self::Oneof => &["oneof"],
Self::View => &["view"],
Self::ViewOneof => &["view", "oneof"],
Self::LazyView => &["lazy_view"],
}
}
}
pub(crate) fn ancillary_prefix(
ctx: &CodeGenContext<'_>,
kind: AncillaryKind,
current_package: &str,
proto_fqn: &str,
from_nesting: usize,
) -> proc_macro2::TokenStream {
use crate::idents::make_field_ident;
use quote::quote;
debug_assert!(
!proto_fqn.starts_with('.'),
"ancillary_prefix expects dotless FQN, got {proto_fqn:?}"
);
let mut supers_tokens = proc_macro2::TokenStream::new();
for _ in 0..from_nesting {
supers_tokens.extend(quote! { super:: });
}
let sentinel = make_field_ident(SENTINEL_MOD);
let kind_segs: Vec<_> = kind
.path_segments()
.iter()
.map(|s| make_field_ident(s))
.collect();
let within_pkg = if current_package.is_empty() {
proto_fqn
} else {
proto_fqn
.strip_prefix(current_package)
.and_then(|s| s.strip_prefix('.'))
.unwrap_or(proto_fqn)
};
let mut fqn = current_package.to_string();
let mut msg_segs = Vec::new();
for name in within_pkg.split('.').filter(|s| !s.is_empty()) {
if !fqn.is_empty() {
fqn.push('.');
}
fqn.push_str(name);
msg_segs.push(make_field_ident(&ctx.message_module_name(&fqn)));
}
quote! { #supers_tokens #sentinel :: #(#kind_segs ::)* #(#msg_segs ::)* }
}
pub(crate) fn matches_proto_prefix(prefix: &str, fqn_dotted: &str) -> bool {
prefix == "."
|| prefix == fqn_dotted
|| (fqn_dotted.starts_with(prefix)
&& fqn_dotted.as_bytes().get(prefix.len()) == Some(&b'.'))
}
fn resolve_file_extern<'p>(
file_name: &str,
file_extern_paths: &'p [(String, String)],
) -> Option<&'p str> {
file_extern_paths
.iter()
.find(|(name, _)| name == file_name)
.map(|(_, rust)| rust.as_str())
}
pub(crate) fn resolve_extern_prefix(
package: &str,
extern_paths: &[(String, String)],
) -> Option<String> {
let dotted = format!(".{}", package);
let mut best: Option<(&str, &str, usize)> = None;
for (proto_prefix, rust_prefix) in extern_paths {
if dotted == *proto_prefix {
return Some(rust_prefix.clone());
}
if let Some(rest) = dotted.strip_prefix(proto_prefix.as_str()) {
if proto_prefix == "." || rest.starts_with('.') {
let prefix_len = proto_prefix.len();
if best.map_or(true, |(_, _, best_len)| prefix_len > best_len) {
best = Some((proto_prefix, rust_prefix, prefix_len));
}
}
}
}
let (proto_prefix, rust_prefix, _) = best?;
let rest = dotted.strip_prefix(proto_prefix)?;
let rest = rest.strip_prefix('.').unwrap_or(rest);
let suffix = rest
.split('.')
.map(to_snake_case)
.collect::<Vec<_>>()
.join("::");
Some(format!("{}::{}", rust_prefix, suffix))
}
pub(crate) fn resolve_extern_type(fqn: &str, extern_paths: &[(String, String)]) -> Option<String> {
if let Some((_, rust)) = extern_paths.iter().find(|(proto, _)| proto == fqn) {
return Some(rust.clone());
}
let mut best: Option<(&str, &str, usize)> = None;
for (proto_prefix, rust_prefix) in extern_paths {
let matches = proto_prefix == "."
|| fqn
.strip_prefix(proto_prefix.as_str())
.is_some_and(|rest| rest.starts_with('.'));
if matches && best.map_or(true, |(_, _, best_len)| proto_prefix.len() > best_len) {
best = Some((proto_prefix, rust_prefix, proto_prefix.len()));
}
}
let (proto_prefix, rust_prefix, _) = best?;
let rest = if proto_prefix == "." {
fqn.strip_prefix('.').unwrap_or(fqn)
} else {
fqn.strip_prefix(proto_prefix)
.and_then(|r| r.strip_prefix('.'))
.unwrap_or("")
};
let mut segments = rest.split('.').collect::<Vec<_>>();
let type_name = segments.pop()?;
let mut path = rust_prefix.to_string();
for module in segments {
path.push_str("::");
path.push_str(&to_snake_case(module));
}
path.push_str("::");
path.push_str(&crate::idents::escape_type_name(type_name));
Some(path)
}
fn join_mod(module: &str, name: &str) -> String {
if module.is_empty() {
name.to_string()
} else {
format!("{module}::{name}")
}
}
fn resolve_type_path(
fqn: &str,
name: &str,
file_root: Option<&str>,
local_module: &str,
extern_paths: &[(String, String)],
type_name_prefix: &str,
) -> (String, bool) {
if let Some((_, rust)) = extern_paths.iter().find(|(proto, _)| proto == fqn) {
(rust.clone(), true)
} else if let Some(root) = file_root {
(join_mod(root, name), true)
} else if let Some(path) = resolve_extern_type(fqn, extern_paths) {
(path, true)
} else {
(
join_mod(
local_module,
&crate::idents::local_type_name(type_name_prefix, name),
),
false,
)
}
}
#[derive(Clone, Copy)]
struct NestedRegistrationCtx<'a> {
package: &'a str,
extern_paths: &'a [(String, String)],
type_name_prefix: &'a str,
}
fn register_nested_types(
type_map: &mut HashMap<String, String>,
package_of: &mut HashMap<String, String>,
module_names: &mut HashMap<String, String>,
reg: NestedRegistrationCtx<'_>,
parent_fqn: &str,
parent_mod: &str,
msg: &crate::generated::descriptor::DescriptorProto,
) {
let NestedRegistrationCtx {
package,
extern_paths,
type_name_prefix,
} = reg;
let extern_override = |fqn: &str| {
extern_paths
.iter()
.find(|(proto, _)| proto == fqn)
.map(|(_, rust)| rust.as_str())
};
let is_local = |name: &&String| extern_override(&format!("{parent_fqn}.{name}")).is_none();
let is_map_entry = |nested: &&crate::generated::descriptor::DescriptorProto| {
nested
.options
.as_option()
.and_then(|o| o.map_entry)
.unwrap_or(false)
};
let local: Vec<String> = msg
.nested_type
.iter()
.filter(|nested| !is_map_entry(nested))
.filter_map(|nested| nested.name.as_ref())
.filter(is_local)
.cloned()
.collect();
let local_modules: HashMap<&str, String> = if local.is_empty() {
HashMap::new()
} else {
let enums = msg.enum_type.iter().filter_map(|e| e.name.as_ref());
let occupied: HashSet<String> = local
.iter()
.chain(enums.filter(is_local))
.map(|name| crate::idents::local_type_name(type_name_prefix, name))
.collect();
let modules = deconflict_modules(&local, &occupied);
local.iter().map(String::as_str).zip(modules).collect()
};
for nested in &msg.nested_type {
if let Some(name) = &nested.name {
let fqn = format!("{}.{}", parent_fqn, name);
let (rust_path, child_mod) = match extern_override(&fqn) {
Some(rust) => {
let module = extern_override_module(name, rust, false);
let child = match rust.rsplit_once("::") {
Some((parent, _)) => format!("{parent}::{module}"),
None => module,
};
(rust.to_string(), child)
}
None => {
let module = local_modules
.get(name.as_str())
.cloned()
.unwrap_or_else(|| to_snake_case(name));
if module != to_snake_case(name) {
module_names.insert(fqn.clone(), module.clone());
}
(
format!(
"{parent_mod}::{}",
crate::idents::local_type_name(type_name_prefix, name)
),
format!("{parent_mod}::{module}"),
)
}
};
type_map.insert(fqn.clone(), rust_path);
package_of.insert(fqn.clone(), package.to_string());
register_nested_types(
type_map,
package_of,
module_names,
reg,
&fqn,
&child_mod,
nested,
);
}
}
for enum_type in &msg.enum_type {
if let Some(name) = &enum_type.name {
let fqn = format!("{}.{}", parent_fqn, name);
let rust_path = extern_override(&fqn).map_or_else(
|| {
format!(
"{parent_mod}::{}",
crate::idents::local_type_name(type_name_prefix, name)
)
},
str::to_string,
);
type_map.insert(fqn.clone(), rust_path);
package_of.insert(fqn, package.to_string());
}
}
}
fn collect_enum_first_values(files: &[FileDescriptorProto]) -> HashMap<String, i32> {
fn record(map: &mut HashMap<String, i32>, prefix: &str, e: &EnumDescriptorProto) {
if let (Some(name), Some(first)) = (e.name.as_deref(), e.value.first()) {
map.insert(format!("{prefix}{name}"), first.number.unwrap_or(0));
}
}
fn walk_msg(map: &mut HashMap<String, i32>, prefix: &str, msg: &DescriptorProto) {
let Some(name) = msg.name.as_deref() else {
return;
};
let child_prefix = format!("{prefix}{name}.");
for e in &msg.enum_type {
record(map, &child_prefix, e);
}
for nested in &msg.nested_type {
walk_msg(map, &child_prefix, nested);
}
}
let mut map = HashMap::new();
for file in files {
let prefix = match file.package.as_deref() {
Some(p) if !p.is_empty() => format!(".{p}."),
_ => ".".to_string(),
};
for e in &file.enum_type {
record(&mut map, &prefix, e);
}
for msg in &file.message_type {
walk_msg(&mut map, &prefix, msg);
}
}
map
}
fn collect_deprecated_enum_values(
files: &[FileDescriptorProto],
) -> HashMap<String, HashSet<String>> {
fn record(map: &mut HashMap<String, HashSet<String>>, prefix: &str, e: &EnumDescriptorProto) {
let Some(name) = e.name.as_deref() else {
return;
};
let fqn = format!("{prefix}{name}");
let deprecated = crate::enumeration::deprecated_items(e);
for (v, _) in e.value.iter().zip(deprecated).filter(|(_, d)| *d) {
if let Some(value_name) = v.name.as_deref() {
map.entry(fqn.clone())
.or_default()
.insert(value_name.to_string());
}
}
}
fn walk_msg(map: &mut HashMap<String, HashSet<String>>, prefix: &str, msg: &DescriptorProto) {
let Some(name) = msg.name.as_deref() else {
return;
};
let child_prefix = format!("{prefix}{name}.");
for e in &msg.enum_type {
record(map, &child_prefix, e);
}
for nested in &msg.nested_type {
walk_msg(map, &child_prefix, nested);
}
}
let mut map = HashMap::new();
for file in files {
let prefix = match file.package.as_deref() {
Some(p) if !p.is_empty() => format!(".{p}."),
_ => ".".to_string(),
};
for e in &file.enum_type {
record(&mut map, &prefix, e);
}
for msg in &file.message_type {
walk_msg(&mut map, &prefix, msg);
}
}
map
}
fn register_enum_closedness(
map: &mut HashMap<String, bool>,
fqn: &str,
parent_features: &ResolvedFeatures,
enum_desc: &EnumDescriptorProto,
) {
let resolved = features::resolve_child(parent_features, features::enum_features(enum_desc));
let closed = resolved.enum_type == features::EnumType::Closed;
map.insert(fqn.to_string(), closed);
}
fn register_nested_enum_closedness(
map: &mut HashMap<String, bool>,
parent_fqn: &str,
parent_features: &ResolvedFeatures,
msg: &DescriptorProto,
) {
let msg_features = features::resolve_child(parent_features, features::message_features(msg));
for enum_type in &msg.enum_type {
if let Some(name) = &enum_type.name {
let fqn = format!("{}.{}", parent_fqn, name);
register_enum_closedness(map, &fqn, &msg_features, enum_type);
}
}
for nested in &msg.nested_type {
if let Some(name) = &nested.name {
let fqn = format!("{}.{}", parent_fqn, name);
register_nested_enum_closedness(map, &fqn, &msg_features, nested);
}
}
}
pub(crate) fn rust_type_key(path: &str) -> String {
match syn::parse_str::<syn::Type>(path) {
Ok(ty) => quote::ToTokens::to_token_stream(&ty).to_string(),
Err(_) => path.to_owned(),
}
}
pub(crate) fn rust_type_name(path: &str) -> Option<String> {
match syn::parse_str::<syn::Type>(path).ok()? {
syn::Type::Path(path) => path
.path
.segments
.last()
.map(|segment| segment.ident.to_string()),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::generated::descriptor::{DescriptorProto, EnumDescriptorProto, FileDescriptorProto};
fn set(names: &[&str]) -> HashSet<String> {
names.iter().map(|s| s.to_string()).collect()
}
fn names(ns: &[&str]) -> Vec<String> {
ns.iter().map(|s| s.to_string()).collect()
}
#[test]
fn deconflict_no_collision_keeps_base() {
let out = deconflict_modules(&names(&["Oof", "Bar"]), &set(&["other"]));
assert_eq!(out, vec!["oof".to_string(), "bar".to_string()]);
}
#[test]
fn deconflict_single_collision_appends_underscore() {
let out = deconflict_modules(&names(&["Oof"]), &set(&["oof"]));
assert_eq!(out, vec!["oof_".to_string()]);
}
#[test]
fn deconflict_repeated_append_when_underscore_slot_also_taken() {
let out = deconflict_modules(&names(&["Oof"]), &set(&["oof", "oof_"]));
assert_eq!(out, vec!["oof__".to_string()]);
}
#[test]
fn deconflict_two_messages_racing_to_same_slot_stay_distinct() {
let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof", "oof_"]));
assert_eq!(out, vec!["oof__".to_string(), "oof___".to_string()]);
let set: HashSet<&String> = out.iter().collect();
assert_eq!(set.len(), out.len());
assert!(!out.contains(&"oof".to_string()) && !out.contains(&"oof_".to_string()));
}
#[test]
fn deconflict_is_independent_of_declaration_order() {
let ch = set(&["oof", "oof_"]);
let fwd = deconflict_modules(&names(&["Oof", "Oof_"]), &ch);
let rev = deconflict_modules(&names(&["Oof_", "Oof"]), &ch);
assert_eq!(fwd, vec!["oof__".to_string(), "oof___".to_string()]);
assert_eq!(rev, vec!["oof___".to_string(), "oof__".to_string()]);
}
#[test]
fn deconflict_avoids_other_messages_raw_base() {
let out = deconflict_modules(&names(&["Oof", "Oof_"]), &set(&["oof"]));
assert_eq!(out, vec!["oof__".to_string(), "oof_".to_string()]);
}
#[test]
fn deconflict_avoids_type_names_and_reserved_names() {
let out = deconflict_modules(
&names(&["item", "Crate", "Arbitrary", "Other"]),
&set(&["item"]),
);
assert_eq!(out, ["item_", "crate_", "arbitrary_", "other"]);
}
#[test]
fn deconflict_suffix_skips_a_type_of_that_name() {
let out = deconflict_modules(&names(&["crate"]), &set(&["crate_"]));
assert_eq!(out, ["crate__"]);
}
#[test]
fn deconflict_order_of_equal_bases_follows_the_proto_name() {
let occupied = set(&["Item", "item"]);
assert_eq!(
deconflict_modules(&names(&["Item", "item"]), &occupied),
["item_", "item__"]
);
assert_eq!(
deconflict_modules(&names(&["item", "Item"]), &occupied),
["item__", "item_"]
);
}
#[test]
fn extern_override_module_follows_the_mapped_type_name() {
let module = |name, path| extern_override_module(name, path, false);
assert_eq!(module("Outer", "::ext::Outer"), "outer");
assert_eq!(module("item", "::ext::item"), "item_");
assert_eq!(module("item", "::ext::Pbitem"), "item");
assert_eq!(module("Crate", "::ext::Crate"), "crate_");
assert_eq!(module("crate", "::ext::crate_"), "crate__");
assert_eq!(module("Oneof", "::ext::outer::Oneof"), "oneof");
assert_eq!(
extern_override_module("Oneof", "::ext::Oneof", true),
"oneof_"
);
}
#[test]
fn deconflict_never_yields_the_sentinel() {
let out = deconflict_modules(&names(&["Buffa"]), &set(&["__buffa", "buffa"]));
assert_eq!(out, vec!["buffa_".to_string()]);
assert_ne!(out[0], SENTINEL_MOD);
}
#[test]
fn child_package_segments_extracts_immediate_segment() {
let pkgs = set(&["foo", "foo.oof", "foo.bar.baz", "foobar"]);
let mut got: Vec<String> = child_package_segments("foo", &pkgs).into_iter().collect();
got.sort();
assert_eq!(got, vec!["bar".to_string(), "oof".to_string()]);
}
fn make_file(
name: &str,
package: &str,
messages: Vec<DescriptorProto>,
enums: Vec<EnumDescriptorProto>,
) -> FileDescriptorProto {
FileDescriptorProto {
name: Some(name.to_string()),
package: if package.is_empty() {
None
} else {
Some(package.to_string())
},
message_type: messages,
enum_type: enums,
..Default::default()
}
}
fn msg(name: &str) -> DescriptorProto {
DescriptorProto {
name: Some(name.to_string()),
..Default::default()
}
}
fn msg_with_nested(name: &str, nested: Vec<DescriptorProto>) -> DescriptorProto {
DescriptorProto {
name: Some(name.to_string()),
nested_type: nested,
..Default::default()
}
}
fn msg_with_nested_and_enums(
name: &str,
nested: Vec<DescriptorProto>,
enums: Vec<EnumDescriptorProto>,
) -> DescriptorProto {
DescriptorProto {
name: Some(name.to_string()),
nested_type: nested,
enum_type: enums,
..Default::default()
}
}
fn enum_desc(name: &str) -> EnumDescriptorProto {
EnumDescriptorProto {
name: Some(name.to_string()),
..Default::default()
}
}
fn enum_with_closed_feature(name: &str) -> EnumDescriptorProto {
use crate::generated::descriptor::{feature_set, EnumOptions, FeatureSet};
EnumDescriptorProto {
name: Some(name.to_string()),
options: buffa::MessageField::some(EnumOptions {
features: buffa::MessageField::some(FeatureSet {
enum_type: Some(feature_set::EnumType::CLOSED),
..Default::default()
}),
..Default::default()
}),
..Default::default()
}
}
fn editions_file(
name: &str,
package: &str,
messages: Vec<DescriptorProto>,
enums: Vec<EnumDescriptorProto>,
) -> FileDescriptorProto {
use crate::generated::descriptor::Edition;
FileDescriptorProto {
name: Some(name.to_string()),
package: Some(package.to_string()),
syntax: Some("editions".to_string()),
edition: Some(Edition::EDITION_2023),
message_type: messages,
enum_type: enums,
..Default::default()
}
}
#[test]
fn test_message_with_package() {
let files = [make_file(
"test.proto",
"my.package",
vec![msg("Foo")],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".my.package.Foo"), Some("my::package::Foo"));
}
#[test]
fn test_message_no_package() {
let files = [make_file("test.proto", "", vec![msg("Bar")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".Bar"), Some("Bar"));
}
#[test]
fn test_nested_message_uses_module_path() {
let outer = msg_with_nested("Outer", vec![msg("Inner")]);
let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.Outer"), Some("pkg::Outer"));
assert_eq!(ctx.rust_type(".pkg.Outer.Inner"), Some("pkg::outer::Inner"));
}
#[test]
fn test_nested_message_no_package() {
let outer = msg_with_nested("Outer", vec![msg("Inner")]);
let files = [make_file("test.proto", "", vec![outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".Outer"), Some("Outer"));
assert_eq!(ctx.rust_type(".Outer.Inner"), Some("outer::Inner"));
}
#[test]
fn test_deeply_nested_message() {
let deep = msg_with_nested("A", vec![msg_with_nested("B", vec![msg("C")])]);
let files = [make_file("test.proto", "pkg", vec![deep], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.A"), Some("pkg::A"));
assert_eq!(ctx.rust_type(".pkg.A.B"), Some("pkg::a::B"));
assert_eq!(ctx.rust_type(".pkg.A.B.C"), Some("pkg::a::b::C"));
}
#[test]
fn test_nested_enum_uses_module_path() {
let outer = msg_with_nested_and_enums("Outer", vec![], vec![enum_desc("Status")]);
let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Outer.Status"),
Some("pkg::outer::Status")
);
}
#[test]
fn test_top_level_enum() {
let files = [make_file(
"test.proto",
"pkg",
vec![],
vec![enum_desc("Status")],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.Status"), Some("pkg::Status"));
}
#[test]
fn test_same_named_nested_types_in_different_parents_are_distinct() {
let outer1 = msg_with_nested("Outer1", vec![msg("Inner")]);
let outer2 = msg_with_nested("Outer2", vec![msg("Inner")]);
let files = [make_file("a.proto", "pkg", vec![outer1, outer2], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Outer1.Inner"),
Some("pkg::outer1::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Outer2.Inner"),
Some("pkg::outer2::Inner")
);
assert_ne!(
ctx.rust_type(".pkg.Outer1.Inner"),
ctx.rust_type(".pkg.Outer2.Inner")
);
}
#[test]
fn test_multiple_files() {
let files = [
make_file("a.proto", "ns.a", vec![msg("MsgA")], vec![]),
make_file("b.proto", "ns.b", vec![msg("MsgB")], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".ns.a.MsgA"), Some("ns::a::MsgA"));
assert_eq!(ctx.rust_type(".ns.b.MsgB"), Some("ns::b::MsgB"));
}
#[test]
fn test_extern_path_exact_per_type_match() {
let files = [make_file(
"test.proto",
"test.pkg",
vec![msg("Msg")],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![(".test.pkg.Msg".into(), "::ext_crate::Msg".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
}
#[test]
fn test_extern_path_per_type_overrides_package_prefix() {
let files = [make_file(
"test.proto",
"test.pkg",
vec![msg("Msg"), msg("Other")],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![
(".test.pkg".into(), "::pkg_crate".into()),
(".test.pkg.Msg".into(), "::ext_crate::Msg".into()),
],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
assert_eq!(ctx.rust_type(".test.pkg.Other"), Some("::pkg_crate::Other"));
}
#[test]
fn test_extern_path_nested_type_inherits_per_type_override() {
let outer = msg_with_nested("Outer", vec![msg("Inner")]);
let files = [make_file("test.proto", "test.pkg", vec![outer], vec![])];
let config = CodeGenConfig {
extern_paths: vec![(".test.pkg.Outer".into(), "::ext::Outer".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".test.pkg.Outer"), Some("::ext::Outer"));
assert_eq!(
ctx.rust_type(".test.pkg.Outer.Inner"),
Some("::ext::outer::Inner")
);
}
#[test]
fn test_extern_path_exact_per_type_enum() {
let files = [make_file(
"test.proto",
"test.pkg",
vec![],
vec![enum_desc("Status")],
)];
let config = CodeGenConfig {
extern_paths: vec![(".test.pkg.Status".into(), "::ext_crate::Status".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".test.pkg.Status"),
Some("::ext_crate::Status")
);
}
#[test]
fn test_extern_path_package_prefix_still_resolves() {
let files = [make_file(
"test.proto",
"test.pkg",
vec![msg("Msg")],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![(".test.pkg".into(), "::pkg_crate".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::pkg_crate::Msg"));
}
#[test]
fn test_extern_path_per_type_does_not_affect_unmapped_type() {
let files = [make_file(
"test.proto",
"test.pkg",
vec![msg("Msg"), msg("Other")],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![(".test.pkg.Msg".into(), "::ext_crate::Msg".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".test.pkg.Msg"), Some("::ext_crate::Msg"));
assert_eq!(ctx.rust_type(".test.pkg.Other"), Some("test::pkg::Other"));
}
#[test]
fn test_keyword_package_segment_in_type_map() {
let files = [make_file(
"latlng.proto",
"google.type",
vec![msg("LatLng")],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".google.type.LatLng"),
Some("google::type::LatLng")
);
}
#[test]
fn test_keyword_package_relative_same_package() {
let files = [make_file(
"latlng.proto",
"google.type",
vec![msg("LatLng"), msg("Expr")],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".google.type.LatLng", "google.type", 0),
Some("LatLng".into())
);
}
#[test]
fn test_keyword_package_cross_package() {
let files = [
make_file("latlng.proto", "google.type", vec![msg("LatLng")], vec![]),
make_file("svc.proto", "google.cloud", vec![msg("Service")], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".google.type.LatLng", "google.cloud", 0),
Some("super::type::LatLng".into())
);
}
#[test]
fn test_keyword_nested_message_module() {
let outer = msg_with_nested("Type", vec![msg("Inner")]);
let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.Type"), Some("pkg::Type"));
assert_eq!(ctx.rust_type(".pkg.Type.Inner"), Some("pkg::type::Inner"));
}
#[test]
fn test_unknown_type_returns_none() {
let files = [make_file("test.proto", "pkg", vec![msg("Foo")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.Unknown"), None);
}
#[test]
fn test_relative_same_package_top_level() {
let files = [make_file("a.proto", "pkg", vec![msg("Foo")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".pkg.Foo", "pkg", 0),
Some("Foo".into())
);
}
#[test]
fn test_relative_cross_package() {
let files = [
make_file("a.proto", "pkg_a", vec![msg("Foo")], vec![]),
make_file("b.proto", "pkg_b", vec![msg("Bar")], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".pkg_a.Foo", "pkg_b", 0),
Some("super::pkg_a::Foo".into())
);
}
#[test]
fn test_relative_no_package() {
let files = [make_file("a.proto", "", vec![msg("Foo")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type_relative(".Foo", "", 0), Some("Foo".into()));
}
#[test]
fn test_relative_unknown_returns_none() {
let files = [make_file("a.proto", "pkg", vec![msg("Foo")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type_relative(".pkg.Unknown", "pkg", 0), None);
}
#[test]
fn test_relative_dotted_package() {
let files = [make_file("a.proto", "my.pkg", vec![msg("Foo")], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".my.pkg.Foo", "my.pkg", 0),
Some("Foo".into())
);
}
#[test]
fn test_relative_cross_dotted_packages() {
let files = [
make_file(
"timestamp.proto",
"google.protobuf",
vec![msg("Timestamp")],
vec![],
),
make_file(
"test.proto",
"protobuf_test_messages.proto3",
vec![msg("TestAllTypesProto3")],
vec![],
),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(
".google.protobuf.Timestamp",
"protobuf_test_messages.proto3",
0,
),
Some("super::super::google::protobuf::Timestamp".into())
);
}
#[test]
fn test_relative_nested_type_from_same_package() {
let outer = msg_with_nested("Outer", vec![msg("Inner")]);
let files = [make_file("test.proto", "pkg", vec![outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".pkg.Outer.Inner", "pkg", 0),
Some("outer::Inner".into())
);
}
#[test]
fn test_nested_module_avoids_the_type_names_of_its_scope() {
let item = msg_with_nested("item", vec![msg("Inner")]);
let outer = msg_with_nested_and_enums(
"Outer",
vec![
msg_with_nested("leaf", vec![msg("Deep")]),
msg_with_nested("Mode", vec![msg("Detail")]),
],
vec![enum_desc("mode")],
);
let files = [make_file("test.proto", "pkg", vec![item, outer], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.item"), Some("pkg::item"));
assert_eq!(ctx.rust_type(".pkg.item.Inner"), Some("pkg::item_::Inner"));
assert_eq!(
ctx.rust_type(".pkg.Outer.leaf.Deep"),
Some("pkg::outer::leaf_::Deep")
);
assert_eq!(
ctx.rust_type(".pkg.Outer.Mode.Detail"),
Some("pkg::outer::mode_::Detail")
);
assert_eq!(ctx.nested_module_name("pkg", "item"), "item_");
assert_eq!(ctx.message_module_name("pkg.Outer"), "outer");
assert_eq!(ctx.message_module_name("pkg.Outer.leaf"), "leaf_");
}
#[test]
fn test_nested_module_of_a_prefixed_type_keeps_its_name() {
let item = msg_with_nested("item", vec![msg("Inner")]);
let files = [make_file("test.proto", "pkg", vec![item], vec![])];
let config = CodeGenConfig {
type_name_prefix: "Pb".to_string(),
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.rust_type(".pkg.item.Inner"), Some("pkg::item::PbInner"));
}
#[test]
fn test_nested_module_named_after_a_path_keyword_gets_a_suffix() {
let files = [make_file(
"test.proto",
"pkg",
vec![
msg_with_nested("Crate", vec![msg("Inner")]),
msg_with_nested("Self", vec![msg("Inner")]),
],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Crate.Inner"),
Some("pkg::crate_::Inner")
);
assert_eq!(ctx.rust_type(".pkg.Self"), Some("pkg::Self_"));
assert_eq!(ctx.rust_type(".pkg.Self.Inner"), Some("pkg::self_::Inner"));
}
#[test]
fn test_reserved_module_names_do_not_depend_on_the_config() {
let files = [make_file(
"test.proto",
"pkg",
vec![
msg_with_nested("Arbitrary", vec![msg("Inner")]),
msg_with_nested("Oneof", vec![msg("Inner")]),
msg_with_nested("Outer", vec![msg_with_nested("Oneof", vec![msg("Inner")])]),
],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Arbitrary.Inner"),
Some("pkg::arbitrary_::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Oneof.Inner"),
Some("pkg::oneof_::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Outer.Oneof.Inner"),
Some("pkg::outer::oneof::Inner")
);
}
#[test]
fn test_top_level_module_avoids_an_enum_in_another_file() {
let mode = || msg_with_nested("Mode", vec![msg("Detail")]);
let same_file = [make_file(
"a.proto",
"pkg",
vec![mode()],
vec![enum_desc("mode")],
)];
let two_files = [
make_file("a.proto", "pkg", vec![mode()], vec![]),
make_file("b.proto", "pkg", vec![], vec![enum_desc("mode")]),
];
let config = CodeGenConfig::default();
for files in [&same_file[..], &two_files[..]] {
let ctx = CodeGenContext::new(files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Mode.Detail"),
Some("pkg::mode_::Detail")
);
}
}
#[test]
fn test_module_avoids_a_sub_package_named_after_a_path_keyword() {
let files = [
make_file(
"a.proto",
"pkg",
vec![msg_with_nested("Crate", vec![msg("Inner")])],
vec![],
),
make_file("b.proto", "pkg.crate", vec![msg("Thing")], vec![]),
make_file(
"c.proto",
"pkg",
vec![msg_with_nested("Arbitrary", vec![msg("Inner")])],
vec![],
),
make_file("d.proto", "pkg.arbitrary", vec![msg("Thing")], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.Crate.Inner"),
Some("pkg::crate__::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Arbitrary.Inner"),
Some("pkg::arbitrary_::Inner")
);
}
#[test]
fn test_extern_package_nested_types_use_the_renamed_modules() {
let files = [
make_file(
"other.proto",
"other",
vec![
msg_with_nested("item", vec![msg("Inner")]),
msg_with_nested("Crate", vec![msg("Inner")]),
msg_with_nested("Outer", vec![msg_with_nested("leaf", vec![msg("Deep")])]),
],
vec![],
),
make_file("local.proto", "local", vec![msg("User")], vec![]),
];
let config = CodeGenConfig {
extern_paths: vec![(".other".into(), "::ext::other".into())],
..Default::default()
};
let ctx = CodeGenContext::for_generate(&files, &["local.proto".to_string()], &config);
assert_eq!(
ctx.rust_type(".other.item.Inner"),
Some("::ext::other::item_::Inner")
);
assert_eq!(
ctx.rust_type(".other.Crate.Inner"),
Some("::ext::other::crate_::Inner")
);
assert_eq!(
ctx.rust_type(".other.Outer.leaf.Deep"),
Some("::ext::other::outer::leaf_::Deep")
);
let split = ctx
.rust_type_relative_split(".other.item.Inner", "local", 0)
.expect("type resolves");
assert_eq!(split.to_package, "::ext::other");
assert_eq!(split.within_package, "item_::Inner");
}
#[test]
fn test_exact_extern_override_nested_types_use_the_renamed_module() {
let files = [make_file(
"test.proto",
"pkg",
vec![
msg_with_nested("item", vec![msg("Inner")]),
msg_with_nested("Crate", vec![msg("Inner")]),
msg_with_nested("Outer", vec![msg_with_nested("leaf", vec![msg("Deep")])]),
],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![
(".pkg.item".into(), "::ext::item".into()),
(".pkg.Crate".into(), "::ext::Crate".into()),
(".pkg.Outer.leaf".into(), "::ext::outer::leaf".into()),
],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".pkg.item.Inner"),
Some("::ext::item_::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Crate.Inner"),
Some("::ext::crate_::Inner")
);
assert_eq!(
ctx.rust_type(".pkg.Outer.leaf.Deep"),
Some("::ext::outer::leaf_::Deep")
);
}
#[test]
fn test_relative_shared_prefix_not_confused() {
let files = [
make_file("ab.proto", "a.b", vec![msg("Msg1")], vec![]),
make_file("abc.proto", "a.bc", vec![msg("Msg2")], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".a.b.Msg1", "a.bc", 0),
Some("super::b::Msg1".into())
);
assert_eq!(
ctx.rust_type_relative(".a.bc.Msg2", "a.b", 0),
Some("super::bc::Msg2".into())
);
}
#[test]
fn test_relative_cross_package_nesting_1() {
let outer = msg_with_nested_and_enums("Business", vec![], vec![enum_desc("Status")]);
let files = [
make_file("admin.proto", "a.b.admin.v1", vec![msg("Svc")], vec![]),
make_file("biz.proto", "a.b.v1", vec![outer], vec![]),
];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".a.b.v1.Business.Status", "a.b.admin.v1", 0),
Some("super::super::v1::business::Status".into())
);
assert_eq!(
ctx.rust_type_relative(".a.b.v1.Business.Status", "a.b.admin.v1", 1),
Some("super::super::super::v1::business::Status".into())
);
}
#[test]
fn test_relative_same_package_nesting_1() {
let files = [make_file(
"test.proto",
"pkg",
vec![msg("Foo"), msg("Bar")],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".pkg.Foo", "pkg", 0),
Some("Foo".into())
);
assert_eq!(
ctx.rust_type_relative(".pkg.Foo", "pkg", 1),
Some("super::Foo".into())
);
assert_eq!(
ctx.rust_type_relative(".pkg.Foo", "pkg", 2),
Some("super::super::Foo".into())
);
}
#[test]
fn test_resolve_file_extern_exact_match_only() {
let mappings = [(
"google/protobuf/descriptor.proto".to_string(),
"::buffa_descriptor::generated::descriptor".to_string(),
)];
assert_eq!(
resolve_file_extern("google/protobuf/descriptor.proto", &mappings),
Some("::buffa_descriptor::generated::descriptor"),
);
assert_eq!(
resolve_file_extern("google/protobuf/timestamp.proto", &mappings),
None,
);
assert_eq!(
resolve_file_extern("vendor/google/protobuf/descriptor.proto", &mappings),
None,
);
}
#[test]
fn test_resolve_extern_prefix_exact_match() {
let result = resolve_extern_prefix(
"my.common",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, Some("::common_protos".into()));
}
#[test]
fn test_resolve_extern_prefix_sub_package() {
let result = resolve_extern_prefix(
"my.common.sub",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, Some("::common_protos::sub".into()));
}
#[test]
fn test_resolve_extern_prefix_no_match() {
let result = resolve_extern_prefix(
"other.pkg",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, None);
}
#[test]
fn test_resolve_extern_prefix_partial_name_no_match() {
let result = resolve_extern_prefix(
"my.commonext",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, None);
}
#[test]
fn test_resolve_extern_prefix_longest_match_wins() {
let result = resolve_extern_prefix(
"my.common.sub",
&[
(".my".into(), "::crate_a".into()),
(".my.common".into(), "::crate_b".into()),
],
);
assert_eq!(result, Some("::crate_b::sub".into()));
}
#[test]
fn test_resolve_extern_prefix_catchall() {
let result = resolve_extern_prefix("greet.v1", &[(".".into(), "crate::proto".into())]);
assert_eq!(result, Some("crate::proto::greet::v1".into()));
}
#[test]
fn test_resolve_extern_prefix_catchall_empty_pkg() {
let result = resolve_extern_prefix("", &[(".".into(), "crate::proto".into())]);
assert_eq!(result, Some("crate::proto".into()));
}
#[test]
fn test_resolve_extern_prefix_catchall_longest_wins() {
let result = resolve_extern_prefix(
"google.protobuf",
&[
(".".into(), "crate::proto".into()),
(
".google.protobuf".into(),
"::buffa_types::google::protobuf".into(),
),
],
);
assert_eq!(result, Some("::buffa_types::google::protobuf".into()));
}
#[test]
fn test_resolve_extern_prefix_catchall_keyword_package() {
let result = resolve_extern_prefix("google.type", &[(".".into(), "crate::proto".into())]);
assert_eq!(result, Some("crate::proto::google::type".into()));
}
#[test]
fn test_resolve_extern_type_exact_match() {
let result = resolve_extern_type(
".google.protobuf.Timestamp",
&[(
".google.protobuf.Timestamp".into(),
"::pbjson_types::Timestamp".into(),
)],
);
assert_eq!(result, Some("::pbjson_types::Timestamp".into()));
}
#[test]
fn test_resolve_extern_type_escapes_a_prefix_mapped_type_name() {
let prefix = [(".other.v1".to_string(), "::other::v1".to_string())];
assert_eq!(
resolve_extern_type(".other.v1.bool", &prefix),
Some("::other::v1::bool_".into())
);
assert_eq!(
resolve_extern_type(".other.v1.type", &prefix),
Some("::other::v1::type_".into())
);
assert_eq!(
resolve_extern_type(".other.v1.Outer.Self", &prefix),
Some("::other::v1::outer::Self_".into())
);
assert_eq!(
resolve_extern_type(
".other.v1.bool",
&[(".other.v1.bool".into(), "::other::Flag".into())]
),
Some("::other::Flag".into())
);
}
#[test]
fn test_resolve_extern_type_exact_wins_over_prefix() {
let result = resolve_extern_type(
".my.pkg.Msg",
&[
(".my.pkg".into(), "::pkg_crate".into()),
(".my.pkg.Msg".into(), "::ext_crate::Msg".into()),
],
);
assert_eq!(result, Some("::ext_crate::Msg".into()));
}
#[test]
fn test_resolve_extern_type_package_prefix_appends_type() {
let result = resolve_extern_type(
".my.common.sub.Msg",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, Some("::common_protos::sub::Msg".into()));
}
#[test]
fn test_resolve_extern_type_catchall() {
let result = resolve_extern_type(".greet.v1.Hello", &[(".".into(), "crate::proto".into())]);
assert_eq!(result, Some("crate::proto::greet::v1::Hello".into()));
}
#[test]
fn test_resolve_extern_type_no_match() {
let result = resolve_extern_type(
".other.pkg.Msg",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, None);
}
#[test]
fn test_resolve_extern_type_partial_name_no_match() {
let result = resolve_extern_type(
".my.commonext.Msg",
&[(".my.common".into(), "::common_protos".into())],
);
assert_eq!(result, None);
}
#[test]
fn test_split_extern_top_level() {
let outer = msg_with_nested("Value", vec![msg("Inner")]);
let files = [make_file(
"struct.proto",
"google.protobuf",
vec![outer],
vec![],
)];
let config = CodeGenConfig::default();
let extern_paths = vec![(
".google.protobuf".into(),
"::buffa_types::google::protobuf".into(),
)];
let ctx = CodeGenContext::new(&files, &config, &extern_paths);
let split = ctx
.rust_type_relative_split(".google.protobuf.Value", "my.pkg", 3)
.expect("type resolves");
assert!(split.is_extern);
assert_eq!(split.to_package, "::buffa_types::google::protobuf");
assert_eq!(split.within_package, "Value");
}
#[test]
fn test_split_extern_nested_type() {
let outer = msg_with_nested("Value", vec![msg("Inner")]);
let files = [make_file(
"struct.proto",
"google.protobuf",
vec![outer],
vec![],
)];
let config = CodeGenConfig::default();
let extern_paths = vec![(
".google.protobuf".into(),
"::buffa_types::google::protobuf".into(),
)];
let ctx = CodeGenContext::new(&files, &config, &extern_paths);
let split = ctx
.rust_type_relative_split(".google.protobuf.Value.Inner", "my.pkg", 0)
.expect("nested type resolves");
assert!(split.is_extern);
assert_eq!(split.to_package, "::buffa_types::google::protobuf");
assert_eq!(split.within_package, "value::Inner");
}
#[test]
fn test_split_per_type_extern_override() {
let outer = msg_with_nested("Outer", vec![msg("Inner")]);
let files = [make_file("custom.proto", "my.pkg", vec![outer], vec![])];
let config = CodeGenConfig {
extern_paths: vec![(".my.pkg.Outer".into(), "::ext::custom::Outer".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
let split = ctx
.rust_type_relative_split(".my.pkg.Outer", "other.pkg", 2)
.expect("overridden type resolves");
assert!(split.is_extern);
assert_eq!(split.to_package, "::ext::custom");
assert_eq!(split.within_package, "Outer");
let nested = ctx
.rust_type_relative_split(".my.pkg.Outer.Inner", "other.pkg", 0)
.expect("nested type resolves");
assert!(nested.is_extern);
assert_eq!(nested.to_package, "::ext::custom");
assert_eq!(nested.within_package, "outer::Inner");
}
#[test]
fn test_extern_path_top_level_message() {
let files = [make_file(
"common.proto",
"my.common",
vec![msg("SharedMsg")],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![(".my.common".into(), "::common_protos".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".my.common.SharedMsg"),
Some("::common_protos::SharedMsg")
);
}
#[test]
fn test_extern_path_nested_message() {
let files = [make_file(
"common.proto",
"my.common",
vec![msg_with_nested("Outer", vec![msg("Inner")])],
vec![],
)];
let config = CodeGenConfig {
extern_paths: vec![(".my.common".into(), "::common_protos".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".my.common.Outer"),
Some("::common_protos::Outer")
);
assert_eq!(
ctx.rust_type(".my.common.Outer.Inner"),
Some("::common_protos::outer::Inner")
);
}
#[test]
fn test_extern_path_nested_types_use_deconflicted_module() {
let money =
msg_with_nested_and_enums("Money", vec![msg("Breakdown")], vec![enum_desc("Currency")]);
let files = [
make_file("lyft_money.proto", "pb.lyft", vec![money], vec![]),
make_file("money.proto", "pb.lyft.money", vec![msg("Money")], vec![]),
make_file(
"users.proto",
"pb.lyft.users",
vec![msg("DailyTotalFares")],
vec![],
),
];
let config = CodeGenConfig {
extern_paths: vec![(".pb.lyft".into(), "::idl_pb_lyft::pb::lyft".into())],
..Default::default()
};
let ctx = CodeGenContext::for_generate(&files, &["users.proto".to_string()], &config);
assert_eq!(
ctx.rust_type(".pb.lyft.Money.Currency"),
Some("::idl_pb_lyft::pb::lyft::money_::Currency")
);
assert_eq!(
ctx.rust_type(".pb.lyft.Money.Breakdown"),
Some("::idl_pb_lyft::pb::lyft::money_::Breakdown")
);
}
#[test]
fn test_extern_path_enum() {
let files = [make_file(
"common.proto",
"my.common",
vec![],
vec![enum_desc("Status")],
)];
let config = CodeGenConfig {
extern_paths: vec![(".my.common".into(), "::common_protos".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".my.common.Status"),
Some("::common_protos::Status")
);
}
#[test]
fn test_extern_path_does_not_affect_other_packages() {
let files = [
make_file("common.proto", "my.common", vec![msg("SharedMsg")], vec![]),
make_file(
"service.proto",
"my.service",
vec![msg("MyService")],
vec![],
),
];
let config = CodeGenConfig {
extern_paths: vec![(".my.common".into(), "::common_protos".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type(".my.common.SharedMsg"),
Some("::common_protos::SharedMsg")
);
assert_eq!(
ctx.rust_type(".my.service.MyService"),
Some("my::service::MyService")
);
}
#[test]
fn test_extern_path_relative_returns_absolute() {
let files = [
make_file("common.proto", "my.common", vec![msg("SharedMsg")], vec![]),
make_file(
"service.proto",
"my.service",
vec![msg("MyService")],
vec![],
),
];
let config = CodeGenConfig {
extern_paths: vec![(".my.common".into(), "::common_protos".into())],
..Default::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(
ctx.rust_type_relative(".my.common.SharedMsg", "my.service", 0),
Some("::common_protos::SharedMsg".into())
);
}
#[test]
fn test_is_enum_closed_proto3_default_open() {
let files = [make_file("a.proto", "p", vec![], vec![enum_desc("E")])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.is_enum_closed(".p.E"), Some(true));
}
#[test]
fn test_is_enum_closed_editions_default_open() {
let files = [editions_file("a.proto", "p", vec![], vec![enum_desc("E")])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.is_enum_closed(".p.E"), Some(false));
}
#[test]
fn test_is_enum_closed_per_enum_override() {
let files = [editions_file(
"a.proto",
"p",
vec![],
vec![enum_desc("Open"), enum_with_closed_feature("Closed")],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.is_enum_closed(".p.Open"), Some(false));
assert_eq!(ctx.is_enum_closed(".p.Closed"), Some(true));
}
#[test]
fn test_is_enum_closed_nested_per_enum_override() {
let files = [editions_file(
"a.proto",
"p",
vec![msg_with_nested_and_enums(
"M",
vec![],
vec![enum_with_closed_feature("Inner")],
)],
vec![],
)];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.is_enum_closed(".p.M.Inner"), Some(true));
}
#[test]
fn test_is_enum_closed_unknown_enum_returns_none() {
let files = [editions_file("a.proto", "p", vec![], vec![])];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert_eq!(ctx.is_enum_closed(".other.Unknown"), None);
}
#[test]
fn test_for_generate_auto_injects_wkt_mapping() {
let ts_msg = DescriptorProto {
name: Some("Timestamp".into()),
..Default::default()
};
let files = [FileDescriptorProto {
name: Some("google/protobuf/timestamp.proto".into()),
package: Some("google.protobuf".into()),
syntax: Some("proto3".into()),
message_type: vec![ts_msg],
..Default::default()
}];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::for_generate(&files, &["other.proto".into()], &config);
assert_eq!(
ctx.rust_type(".google.protobuf.Timestamp"),
Some("::buffa_types::google::protobuf::Timestamp"),
"WKT auto-mapping must be applied via for_generate"
);
}
#[test]
fn test_for_generate_suppresses_wkt_when_generating_wkt() {
let ts_msg = DescriptorProto {
name: Some("Timestamp".into()),
..Default::default()
};
let files = [FileDescriptorProto {
name: Some("google/protobuf/timestamp.proto".into()),
package: Some("google.protobuf".into()),
syntax: Some("proto3".into()),
message_type: vec![ts_msg],
..Default::default()
}];
let config = CodeGenConfig::default();
let ctx = CodeGenContext::for_generate(
&files,
&["google/protobuf/timestamp.proto".into()],
&config,
);
assert_eq!(
ctx.rust_type(".google.protobuf.Timestamp"),
Some("google::protobuf::Timestamp")
);
}
#[test]
fn test_matching_attributes_catchall() {
let attrs = vec![(".".into(), "#[derive(Foo)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.to_string().contains("derive"));
}
#[test]
fn test_matching_attributes_exact_match() {
let attrs = vec![(".my.pkg.MyMessage".into(), "#[derive(Bar)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.to_string().contains("derive"));
}
#[test]
fn test_matching_attributes_package_prefix() {
let attrs = vec![(".my.pkg".into(), "#[derive(Baz)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.to_string().contains("derive"));
}
#[test]
fn test_matching_attributes_no_partial_segment_match() {
let attrs = vec![(".my.pk".into(), "#[derive(Bad)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.is_empty());
}
#[test]
fn test_matching_attributes_no_match() {
let attrs = vec![(".other.pkg".into(), "#[derive(Nope)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.is_empty());
}
#[test]
fn test_matching_attributes_multiple_accumulate() {
let attrs = vec![
(".".into(), "#[derive(A)]".into()),
(".my.pkg".into(), "#[derive(B)]".into()),
];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
let s = result.to_string();
assert!(s.contains("A") && s.contains("B"));
}
#[test]
fn test_matching_attributes_invalid_attr_errors() {
let attrs = vec![(".".into(), "not valid {{{{".into())];
let err = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap_err();
assert!(matches!(
err,
crate::CodeGenError::InvalidCustomAttribute { .. }
));
}
fn attribute_error_detail(attribute: &str) -> String {
let attrs = vec![(".my.pkg".to_string(), attribute.to_string())];
match CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg") {
Err(crate::CodeGenError::InvalidCustomAttribute {
path,
attribute: reported,
detail,
}) => {
assert_eq!(path, ".my.pkg");
assert_eq!(reported, attribute);
detail
}
other => panic!("{attribute:?}: expected InvalidCustomAttribute, got {other:?}"),
}
}
#[test]
fn test_matching_attributes_rejects_tokens_that_are_not_outer_attributes() {
for attribute in [
"serde(skip)",
"pub extra: u32,",
"#[derive(A)] pub extra: u32,",
"#[derive(A)] serde(skip)",
"derive(A) #[derive(B)]",
] {
assert_eq!(
attribute_error_detail(attribute),
"expected an outer attribute of the form `#[...]`",
"{attribute:?}"
);
}
}
#[test]
fn test_matching_attributes_rejects_an_inner_attribute() {
for attribute in ["#![allow(dead_code)]", "//! Module docs."] {
assert_eq!(
attribute_error_detail(attribute),
"an inner attribute `#![...]` is not accepted; write `#[...]`",
"{attribute:?}"
);
}
}
#[test]
fn test_matching_attributes_rejects_a_string_without_an_attribute() {
for attribute in ["", " \n"] {
assert_eq!(
attribute_error_detail(attribute),
"expected at least one `#[...]` attribute",
"{attribute:?}"
);
}
}
#[test]
fn test_matching_attributes_multiple_in_one_string() {
let attrs = vec![(
".".into(),
"/// Doc.\n#[derive(A)] #[serde(rename = \"b\")] \
#[cfg_attr(feature = \"json\", serde(default))]"
.into(),
)];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap();
let parsed: syn::ItemStruct = syn::parse2(quote::quote!(#result struct S;)).unwrap();
let paths: Vec<String> = parsed
.attrs
.iter()
.map(|attr| attr.path().get_ident().unwrap().to_string())
.collect();
assert_eq!(paths, ["doc", "derive", "serde", "cfg_attr"]);
}
#[test]
fn test_matches_proto_prefix_catchall() {
assert!(matches_proto_prefix(".", ".anything.here"));
assert!(matches_proto_prefix(".", "."));
}
#[test]
fn test_matches_proto_prefix_segment_boundary() {
assert!(!matches_proto_prefix(".my.pk", ".my.pkg.Msg"));
assert!(matches_proto_prefix(".my.pkg", ".my.pkg.Msg"));
}
fn resolve_deny_unknown_json(global: bool, rules: &[(&str, bool)], fqns: &[&str]) -> Vec<bool> {
let files = [make_file("t.proto", "test", vec![msg("Outer")], vec![])];
let config = CodeGenConfig {
deny_unknown_json_fields: global,
deny_unknown_json_fields_in: rules
.iter()
.map(|(path, enabled)| ((*path).to_string(), *enabled))
.collect(),
..CodeGenConfig::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
fqns.iter()
.map(|f| ctx.deny_unknown_json_fields(f))
.collect()
}
#[test]
fn deny_unknown_json_fields_defaults_to_lenient() {
assert_eq!(
resolve_deny_unknown_json(false, &[], &["test.Outer"]),
[false]
);
}
#[test]
fn deny_unknown_json_fields_last_matching_rule_wins() {
let config = CodeGenConfig {
deny_unknown_json_fields: false,
deny_unknown_json_fields_in: vec![
(".test".to_string(), true),
(".test.Lenient".to_string(), false),
],
..CodeGenConfig::default()
};
let files = [make_file(
"t.proto",
"test",
vec![msg("Strict"), msg("Lenient")],
vec![],
)];
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert!(ctx.deny_unknown_json_fields("test.Strict"));
assert!(ctx.deny_unknown_json_fields(".test.Strict"));
assert!(!ctx.deny_unknown_json_fields("test.Lenient"));
assert!(!ctx.deny_unknown_json_fields("test.Lenient.Child"));
assert!(!ctx.deny_unknown_json_fields("other.Msg"));
}
#[test]
fn deny_unknown_json_fields_parent_rule_covers_nested_messages() {
let got = resolve_deny_unknown_json(
false,
&[(".test.Outer", true)],
&[
"test.Outer",
"test.Outer.Inner",
"test.Outer.Inner.Deep",
"test.OuterX",
"test.Other",
],
);
assert_eq!(got, [true, true, true, false, false]);
}
#[test]
fn deny_unknown_json_fields_child_rule_does_not_enable_parent() {
let got = resolve_deny_unknown_json(
false,
&[(".test.Outer.Inner", true)],
&["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"],
);
assert_eq!(got, [false, true, true]);
}
#[test]
fn preserve_unknown_fields_path_override_last_match_wins() {
let files = [make_file(
"t.proto",
"test",
vec![msg("Keep"), msg("Drop"), msg("Nested")],
vec![],
)];
let config = CodeGenConfig {
preserve_unknown_fields: false,
preserve_unknown_fields_in: vec![
(".test".to_string(), true),
(".test.Drop".to_string(), false),
],
..CodeGenConfig::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
assert!(ctx.preserve_unknown_fields("test.Keep"));
assert!(ctx.preserve_unknown_fields(".test.Keep"));
assert!(!ctx.preserve_unknown_fields("test.Drop"));
assert!(ctx.preserve_unknown_fields("test.Keep.Nested"));
assert!(!ctx.preserve_unknown_fields("test.Drop.Child"));
assert!(!ctx.preserve_unknown_fields("other.Msg"));
}
fn resolve_preserve(global: bool, rules: &[(&str, bool)], fqns: &[&str]) -> Vec<bool> {
let files = [make_file("t.proto", "test", vec![msg("Outer")], vec![])];
let config = CodeGenConfig {
preserve_unknown_fields: global,
preserve_unknown_fields_in: rules
.iter()
.map(|(path, enabled)| ((*path).to_string(), *enabled))
.collect(),
..CodeGenConfig::default()
};
let ctx = CodeGenContext::new(&files, &config, &config.extern_paths);
fqns.iter()
.map(|f| ctx.preserve_unknown_fields(f))
.collect()
}
#[test]
fn preserve_unknown_fields_child_rule_does_not_enable_parent() {
let got = resolve_preserve(
false,
&[(".test.Outer.Inner", true)],
&["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"],
);
assert_eq!(got, [false, true, true]);
}
#[test]
fn preserve_unknown_fields_parent_rule_covers_nested_messages() {
let got = resolve_preserve(
false,
&[(".test.Outer", true)],
&[
"test.Outer",
"test.Outer.Inner",
"test.Outer.Inner.Deep",
"test.OuterX",
"test.Other",
],
);
assert_eq!(got, [true, true, true, false, false]);
}
#[test]
fn preserve_unknown_fields_later_rule_carves_out_nested_message() {
let fqns = ["test.Outer", "test.Outer.Inner", "test.Outer.Inner.Deep"];
let got = resolve_preserve(
false,
&[(".test.Outer", true), (".test.Outer.Inner", false)],
&fqns,
);
assert_eq!(got, [true, false, false]);
let got = resolve_preserve(
false,
&[(".test.Outer.Inner", false), (".test.Outer", true)],
&fqns,
);
assert_eq!(got, [true, true, true]);
}
#[test]
fn preserve_unknown_fields_rules_can_disable_under_global_on() {
let got = resolve_preserve(
true,
&[(".test.Drop", false)],
&["test.Keep", "test.Drop", "test.Drop.Child"],
);
assert_eq!(got, [true, false, false]);
}
}