diff --git a/.changes/unreleased/added-20261122-181800.yaml b/.changes/unreleased/added-20261122-181800.yaml new file mode 100644 index 00000000..d9ce6d10 --- /dev/null +++ b/.changes/unreleased/added-20261122-181800.yaml @@ -0,0 +1,4 @@ +kind: Added +body: |- + **Warn when a custom attribute rule matches no generated element** (closes #697). `generate_with_diagnostics` now emits `CodeGenWarning::AttributeRuleMatchedNothing { rule, option }` for any entry in `type_attributes`, `field_attributes`, `message_attributes`, `enum_attributes`, `oneof_attributes`, or `oneof_struct_field_attributes` that matched no element generated by the run, surfacing typos and wrong-kind paths (such as a variant path passed to `oneof_struct_field_attributes`) at build time. +time: 2026-11-22T18:18:00+09:00 diff --git a/buffa-codegen/src/context.rs b/buffa-codegen/src/context.rs index 78a2e9bf..90f55f02 100644 --- a/buffa-codegen/src/context.rs +++ b/buffa-codegen/src/context.rs @@ -122,6 +122,9 @@ pub struct CodeGenContext<'a> { /// /// [`generate_with_diagnostics`]: crate::generate_with_diagnostics warnings: std::cell::RefCell>, + /// Per-rule match flags for the six custom attribute lists in `config`, + /// indexed by [`AttributeOption`] discriminant. + matched_attributes: std::cell::RefCell<[Vec; 6]>, /// The messages generated with the table codec, planned by /// [`plan_table_codec`](Self::plan_table_codec). Unset, which is the same /// as empty, unless a table codec was requested. @@ -338,6 +341,49 @@ fn parse_custom_attribute( /// Checks every custom attribute rule of `config`, in the order of its six /// attribute lists, whether or not the rule's path matches a generated item. +#[derive(Clone, Copy, Debug)] +pub(crate) enum AttributeOption { + Type = 0, + Field = 1, + Message = 2, + Enum = 3, + Oneof = 4, + OneofStructField = 5, +} + +impl AttributeOption { + const ALL: [Self; 6] = [ + Self::Type, + Self::Field, + Self::Message, + Self::Enum, + Self::Oneof, + Self::OneofStructField, + ]; + + pub(crate) const fn option_name(self) -> &'static str { + match self { + Self::Type => "type_attributes", + Self::Field => "field_attributes", + Self::Message => "message_attributes", + Self::Enum => "enum_attributes", + Self::Oneof => "oneof_attributes", + Self::OneofStructField => "oneof_struct_field_attributes", + } + } + + fn rules(self, config: &crate::CodeGenConfig) -> &[(String, String)] { + match self { + Self::Type => &config.type_attributes, + Self::Field => &config.field_attributes, + Self::Message => &config.message_attributes, + Self::Enum => &config.enum_attributes, + Self::Oneof => &config.oneof_attributes, + Self::OneofStructField => &config.oneof_struct_field_attributes, + } + } +} + pub(crate) fn validate_custom_attributes( config: &crate::CodeGenConfig, ) -> Result<(), crate::CodeGenError> { @@ -672,6 +718,14 @@ impl<'a> CodeGenContext<'a> { keyword_field_renames: keyword_plan.field_renames, keyword_oneof_renames: keyword_plan.oneof_renames, warnings: std::cell::RefCell::new(plan_warnings), + matched_attributes: std::cell::RefCell::new([ + vec![false; config.type_attributes.len()], + vec![false; config.field_attributes.len()], + vec![false; config.message_attributes.len()], + vec![false; config.enum_attributes.len()], + vec![false; config.oneof_attributes.len()], + vec![false; config.oneof_struct_field_attributes.len()], + ]), imports: std::cell::RefCell::new(crate::imports::ImportsPhase::Off), } } @@ -1270,6 +1324,7 @@ impl<'a> CodeGenContext<'a> { /// /// Returns `CodeGenError::InvalidCustomAttribute` if any matching attribute /// string does not parse as one or more `#[...]` attributes. + #[cfg(test)] pub(crate) fn matching_attributes( attrs: &[(String, String)], fqn: &str, @@ -1287,6 +1342,48 @@ impl<'a> CodeGenContext<'a> { Ok(tokens) } + /// Collect custom attributes for `option` matching `fqn`, recording every + /// matched rule so [`warn_unmatched_attributes`](Self::warn_unmatched_attributes) + /// can report rules that matched nothing. + pub(crate) fn matching_attributes_for( + &self, + option: AttributeOption, + fqn: &str, + ) -> Result { + let attrs = option.rules(self.config); + if attrs.is_empty() { + return Ok(proc_macro2::TokenStream::new()); + } + let fqn_dotted = format!(".{fqn}"); + let mut tokens = proc_macro2::TokenStream::new(); + let mut matched = self.matched_attributes.borrow_mut(); + let flags = &mut matched[option as usize]; + for (idx, (prefix, attr_str)) in attrs.iter().enumerate() { + if matches_proto_prefix(prefix, &fqn_dotted) { + flags[idx] = true; + tokens.extend(parse_custom_attribute(prefix, attr_str)?); + } + } + Ok(tokens) + } + + /// Emit [`CodeGenWarning::AttributeRuleMatchedNothing`] for every custom + /// attribute rule that matched no generated element during this run. + pub(crate) fn warn_unmatched_attributes(&self) { + let matched = self.matched_attributes.borrow(); + for option in AttributeOption::ALL { + let flags = &matched[option as usize]; + for ((rule, _), &was_matched) in option.rules(self.config).iter().zip(flags.iter()) { + if !was_matched { + self.warn(crate::CodeGenWarning::AttributeRuleMatchedNothing { + rule: rule.clone(), + option: option.option_name(), + }); + } + } + } + } + /// Resolve the [`BytesRepr`](crate::BytesRepr) for a `bytes` field at the /// given proto path. /// diff --git a/buffa-codegen/src/enumeration.rs b/buffa-codegen/src/enumeration.rs index 2d5bec97..d78fd720 100644 --- a/buffa-codegen/src/enumeration.rs +++ b/buffa-codegen/src/enumeration.rs @@ -370,14 +370,10 @@ pub fn generate_enum( crate::comments::doc_attrs_resolved(ctx.comment(proto_fqn), proto_fqn, &ctx.type_map); quote! { #base #idiomatic_doc_note } }; - let custom_type_attrs = crate::context::CodeGenContext::matching_attributes( - &ctx.config.type_attributes, - proto_fqn, - )?; - let custom_enum_attrs = crate::context::CodeGenContext::matching_attributes( - &ctx.config.enum_attributes, - proto_fqn, - )?; + let custom_type_attrs = + ctx.matching_attributes_for(crate::context::AttributeOption::Type, proto_fqn)?; + let custom_enum_attrs = + ctx.matching_attributes_for(crate::context::AttributeOption::Enum, proto_fqn)?; // A `skip_debug` rule naming the enum leaves `Debug` to the consuming // crate. diff --git a/buffa-codegen/src/lib.rs b/buffa-codegen/src/lib.rs index a235b496..620f07fb 100644 --- a/buffa-codegen/src/lib.rs +++ b/buffa-codegen/src/lib.rs @@ -2484,6 +2484,28 @@ pub enum CodeGenWarning { /// so, in place of the path hint. matches_ungenerated: bool, }, + /// A custom attribute rule in [`type_attributes`](CodeGenConfig::type_attributes), + /// [`field_attributes`](CodeGenConfig::field_attributes), + /// [`message_attributes`](CodeGenConfig::message_attributes), + /// [`enum_attributes`](CodeGenConfig::enum_attributes), + /// [`oneof_attributes`](CodeGenConfig::oneof_attributes), or + /// [`oneof_struct_field_attributes`](CodeGenConfig::oneof_struct_field_attributes) + /// matched no element generated by this call, so the attribute was never + /// emitted. + /// + /// Usually a typo, a variant path passed to `oneof_struct_field_attributes` + /// instead of the oneof path, a missing leading dot, or a path targeting a + /// type mapped through `extern_path` or `exclude_packages`. + #[non_exhaustive] + AttributeRuleMatchedNothing { + /// The rule's path as configured. + rule: String, + /// The [`CodeGenConfig`] list that contains the rule: + /// `"type_attributes"`, `"field_attributes"`, `"message_attributes"`, + /// `"enum_attributes"`, `"oneof_attributes"`, or + /// `"oneof_struct_field_attributes"`. + option: &'static str, + }, /// A [`codec_strategy_in`](CodeGenConfig::codec_strategy_in) rule matched no /// message being generated, so it changed nothing. Usually a typo, a field /// path instead of a message path, or a rule for a package mapped through @@ -2747,6 +2769,13 @@ impl core::fmt::Display for CodeGenWarning { ) } } + Self::AttributeRuleMatchedNothing { rule, option } => { + write!( + f, + "{option} rule '{rule}' matched no generated element, so the attribute \ + was not emitted — check the fully-qualified proto path and target kind" + ) + } } } } @@ -3750,6 +3779,7 @@ pub fn generate_with_diagnostics( )?; } + ctx.warn_unmatched_attributes(); Ok((output, ctx.take_warnings())) } @@ -5758,5 +5788,142 @@ pub enum CodeGenError { }, } +#[cfg(test)] +mod attribute_rule_warning_tests { + use super::generated::descriptor::{ + field_descriptor_proto, DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, + FieldDescriptorProto, FileDescriptorProto, OneofDescriptorProto, + }; + use super::{generate_with_diagnostics, CodeGenConfig, CodeGenWarning}; + + fn sample_descriptor() -> (Vec, Vec) { + let fd = FileDescriptorProto { + name: Some("sample.proto".into()), + package: Some("my.pkg".into()), + syntax: Some("proto3".into()), + enum_type: vec![EnumDescriptorProto { + name: Some("Status".into()), + value: vec![EnumValueDescriptorProto { + name: Some("STATUS_UNSPECIFIED".into()), + number: Some(0), + ..Default::default() + }], + ..Default::default() + }], + message_type: vec![DescriptorProto { + name: Some("Msg".into()), + oneof_decl: vec![OneofDescriptorProto { + name: Some("kind".into()), + ..Default::default() + }], + field: vec![ + FieldDescriptorProto { + name: Some("secret".into()), + number: Some(1), + label: Some(field_descriptor_proto::Label::LABEL_OPTIONAL), + r#type: Some(field_descriptor_proto::Type::TYPE_STRING), + json_name: Some("secret".into()), + ..Default::default() + }, + FieldDescriptorProto { + name: Some("text".into()), + number: Some(2), + label: Some(field_descriptor_proto::Label::LABEL_OPTIONAL), + r#type: Some(field_descriptor_proto::Type::TYPE_STRING), + oneof_index: Some(0), + json_name: Some("text".into()), + ..Default::default() + }, + ], + ..Default::default() + }], + ..Default::default() + }; + (vec![fd], vec!["sample.proto".into()]) + } + + #[test] + fn matching_attribute_rules_produce_no_warnings() { + let (files, to_gen) = sample_descriptor(); + let mut config = CodeGenConfig::default(); + config + .type_attributes + .push((".my.pkg.Msg".into(), "#[allow(dead_code)]".into())); + config + .message_attributes + .push((".my.pkg.Msg".into(), "#[allow(dead_code)]".into())); + config + .enum_attributes + .push((".my.pkg.Status".into(), "#[allow(dead_code)]".into())); + config + .oneof_attributes + .push((".my.pkg.Msg.kind".into(), "#[allow(dead_code)]".into())); + config + .oneof_struct_field_attributes + .push((".my.pkg.Msg.kind".into(), "#[allow(dead_code)]".into())); + config + .field_attributes + .push((".my.pkg.Msg.secret".into(), "#[allow(dead_code)]".into())); + config + .field_attributes + .push((".my.pkg.Msg.kind.text".into(), "#[allow(dead_code)]".into())); + + let (_, warnings) = generate_with_diagnostics(&files, &to_gen, &config).unwrap(); + assert!( + warnings.is_empty(), + "expected no warnings, got: {warnings:?}" + ); + } + + #[test] + fn unmatched_attribute_rules_warn_with_option_and_rule() { + let (files, to_gen) = sample_descriptor(); + let mut config = CodeGenConfig::default(); + config + .type_attributes + .push((".my.pkg.MissingType".into(), "#[allow(dead_code)]".into())); + config + .field_attributes + .push((".my.pkg.Mesage.secret".into(), "#[allow(dead_code)]".into())); + config + .message_attributes + .push((".my.pkg.Status".into(), "#[allow(dead_code)]".into())); + config + .enum_attributes + .push((".my.pkg.Msg".into(), "#[allow(dead_code)]".into())); + config + .oneof_attributes + .push((".my.pkg.Msg.missing".into(), "#[allow(dead_code)]".into())); + config + .oneof_struct_field_attributes + .push((".my.pkg.Msg.kind.text".into(), "#[allow(dead_code)]".into())); + + let (_, warnings) = generate_with_diagnostics(&files, &to_gen, &config).unwrap(); + let got: Vec<(&str, &str)> = warnings + .iter() + .filter_map(|w| match w { + CodeGenWarning::AttributeRuleMatchedNothing { rule, option } => { + Some((*option, rule.as_str())) + } + _ => None, + }) + .collect(); + assert_eq!( + got, + vec![ + ("type_attributes", ".my.pkg.MissingType"), + ("field_attributes", ".my.pkg.Mesage.secret"), + ("message_attributes", ".my.pkg.Status"), + ("enum_attributes", ".my.pkg.Msg"), + ("oneof_attributes", ".my.pkg.Msg.missing"), + ("oneof_struct_field_attributes", ".my.pkg.Msg.kind.text"), + ] + ); + for w in &warnings { + assert!(w.to_string().contains("matched no generated element")); + } + } +} + #[cfg(test)] mod tests; diff --git a/buffa-codegen/src/message.rs b/buffa-codegen/src/message.rs index cdf3de40..525cb26b 100644 --- a/buffa-codegen/src/message.rs +++ b/buffa-codegen/src/message.rs @@ -281,8 +281,8 @@ fn generate_message_with_nesting( let rename_note = ctx .oneof_rename_note(oneof_name) .map(|note| quote! { #[doc = #note] }); - let custom_attrs = CodeGenContext::matching_attributes( - &ctx.config.oneof_struct_field_attributes, + let custom_attrs = ctx.matching_attributes_for( + crate::context::AttributeOption::OneofStructField, &format!("{proto_fqn}.{oneof_name}"), )?; let tokens = quote! { @@ -575,9 +575,9 @@ fn generate_message_with_nesting( quote! {} }; let custom_type_attrs = - CodeGenContext::matching_attributes(&ctx.config.type_attributes, proto_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Type, proto_fqn)?; let custom_message_attrs = - CodeGenContext::matching_attributes(&ctx.config.message_attributes, proto_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Message, proto_fqn)?; let custom_deserialize = if needs_custom_deserialize { crate::feature_gates::cfg_block( generate_custom_deserialize( @@ -2046,7 +2046,7 @@ fn generate_field( quote! {} }; let custom_field_attrs = - CodeGenContext::matching_attributes(&ctx.config.field_attributes, &field_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Field, &field_fqn)?; // Deprecation reaches a generated field from two sources: the // `[deprecated = true]` option, and a caller-supplied `#[deprecated]` from // `field_attribute` (the documented workaround for the option having been diff --git a/buffa-codegen/src/oneof.rs b/buffa-codegen/src/oneof.rs index d8a615a9..e5d2bb54 100644 --- a/buffa-codegen/src/oneof.rs +++ b/buffa-codegen/src/oneof.rs @@ -409,7 +409,7 @@ fn collect_variant_info( }; let variant_fqn = format!("{proto_fqn}.{oneof_name}.{proto_name}"); let custom_attrs = - CodeGenContext::matching_attributes(&ctx.config.field_attributes, &variant_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Field, &variant_fqn)?; // Recursive variants never make it into the resolved unboxed set // (see `resolve_unboxed_variants`), so a variant that an // *exact-path* rule names but that is still boxed can only have @@ -628,7 +628,7 @@ pub fn generate_oneof_enum( let oneof_doc = crate::comments::doc_attrs_resolved(ctx.comment(&oneof_fqn), proto_fqn, &ctx.type_map); let custom_type_attrs = - CodeGenContext::matching_attributes(&ctx.config.type_attributes, &oneof_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Type, &oneof_fqn)?; // An inline (unboxed) message variant can dwarf its siblings, which trips // clippy::large_enum_variant in the consumer's crate on code they cannot // edit. The user explicitly chose inline storage, so allow the lint — @@ -643,7 +643,7 @@ pub fn generate_oneof_enum( quote! {} }; let custom_oneof_attrs = - CodeGenContext::matching_attributes(&ctx.config.oneof_attributes, &oneof_fqn)?; + ctx.matching_attributes_for(crate::context::AttributeOption::Oneof, &oneof_fqn)?; // Variants whose field is `[debug_redact = true]` print a placeholder // instead of their payload. The `Debug` derive is swapped for a manual