Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
kind: Fixed
body: |-
**Warn when a custom attribute rule matches no generated target** (#697). All six attribute lists report the list and proto path for each unmatched entry, including typos and oneof variant paths used with `oneof_struct_field_attribute`. Generated Rust and malformed-attribute validation are unchanged.
time: 2026-10-15T19:32:57.937901+00:00
9 changes: 7 additions & 2 deletions buffa-build/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1773,6 +1773,11 @@ impl Config {
/// [`compile`](Self::compile) fail with
/// [`CodeGenError::InvalidCustomAttribute`](buffa_codegen::CodeGenError),
/// whether or not `path` matches a generated type.
/// A valid rule matching no generated type emits a build warning naming
/// the attribute list and path. The same applies to the other five custom
/// attribute methods, each using its own target set. Rules are checked
/// across all files in this compilation. Descriptors used only as imports,
/// excluded files and generated view families do not supply targets.
///
/// Multiple calls accumulate in insertion order — all matching attributes
/// are emitted, and ordering is preserved in generated code.
Expand Down Expand Up @@ -2036,8 +2041,8 @@ impl Config {
/// [`compile`](Self::compile) fail.
///
/// A rule on a variant's path (`.my.pkg.MyMessage.my_oneof.variant_name`)
/// does not match the oneof, so it has no effect, and the build does not
/// warn about it. Variants take their attributes from
/// does not match the oneof, so it has no effect and emits an unmatched-rule
/// build warning. Variants take their attributes from
/// [`field_attribute`](Self::field_attribute).
///
/// Each of these lines of the generated code for a oneof takes its
Expand Down
128 changes: 117 additions & 11 deletions buffa-codegen/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,43 @@ pub struct SplitPath {
pub is_extern: bool,
}

/// An attribute list and its distinct generated target set.
#[derive(Clone, Copy)]
pub(crate) enum CustomAttributeKind {
Type,
Message,
Enum,
Oneof,
Field,
OneofStructField,
}

impl CustomAttributeKind {
// This order also determines unmatched-rule diagnostic order.
const ALL: [Self; 6] = [
Self::Type,
Self::Message,
Self::Enum,
Self::Oneof,
Self::Field,
Self::OneofStructField,
];

fn rules(self, config: &CodeGenConfig) -> (&'static str, &[(String, String)]) {
match self {
Self::Type => ("type_attributes", &config.type_attributes),
Self::Message => ("message_attributes", &config.message_attributes),
Self::Enum => ("enum_attributes", &config.enum_attributes),
Self::Oneof => ("oneof_attributes", &config.oneof_attributes),
Self::Field => ("field_attributes", &config.field_attributes),
Self::OneofStructField => (
"oneof_struct_field_attributes",
&config.oneof_struct_field_attributes,
),
}
}
}

/// Shared context for a code generation run.
///
/// Holds the full set of file descriptors and a mapping from fully-qualified
Expand Down Expand Up @@ -122,6 +159,9 @@ pub struct CodeGenContext<'a> {
///
/// [`generate_with_diagnostics`]: crate::generate_with_diagnostics
warnings: std::cell::RefCell<Vec<crate::CodeGenWarning>>,
/// One bit per list entry, set only where custom attributes are emitted.
/// Indexing entries rather than paths preserves duplicate rules.
custom_attribute_matches: [Vec<std::cell::Cell<bool>>; 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.
Expand Down Expand Up @@ -672,6 +712,8 @@ 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),
custom_attribute_matches: CustomAttributeKind::ALL
.map(|kind| vec![std::cell::Cell::new(false); kind.rules(config).1.len()]),
imports: std::cell::RefCell::new(crate::imports::ImportsPhase::Off),
}
}
Expand Down Expand Up @@ -1271,22 +1313,50 @@ impl<'a> CodeGenContext<'a> {
/// Returns `CodeGenError::InvalidCustomAttribute` if any matching attribute
/// string does not parse as one or more `#[...]` attributes.
pub(crate) fn matching_attributes(
attrs: &[(String, String)],
&self,
kind: CustomAttributeKind,
fqn: &str,
) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
let (_, attrs) = kind.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();
for (prefix, attr_str) in attrs {
for (index, (prefix, attr_str)) in attrs.iter().enumerate() {
if matches_proto_prefix(prefix, &fqn_dotted) {
tokens.extend(parse_custom_attribute(prefix, attr_str)?);
// The import-collection pass discards its generated tokens;
// only the subsequent real emission counts as a match.
if !matches!(
*self.imports.borrow(),
crate::imports::ImportsPhase::Collecting(_)
) {
self.custom_attribute_matches[kind as usize][index].set(true);
}
}
}
Ok(tokens)
}

/// Report inert entries after every requested package has been generated.
pub(crate) fn warn_unmatched_custom_attributes(&self) {
for kind in CustomAttributeKind::ALL {
let (option, rules) = kind.rules(self.config);
for ((rule, _), matched) in rules
.iter()
.zip(&self.custom_attribute_matches[kind as usize])
{
if !matched.get() {
self.warn(crate::CodeGenWarning::CustomAttributeRuleMatchedNothing {
option,
rule: rule.clone(),
});
}
}
}
}

/// Resolve the [`BytesRepr`](crate::BytesRepr) for a `bytes` field at the
/// given proto path.
///
Expand Down Expand Up @@ -3660,40 +3730,76 @@ mod tests {

// ── matching_attributes tests ──────────────────────────────────────

fn matching_attributes(
attrs: &[(String, String)],
fqn: &str,
) -> Result<proc_macro2::TokenStream, crate::CodeGenError> {
let config = CodeGenConfig {
type_attributes: attrs.to_vec(),
..CodeGenConfig::default()
};
CodeGenContext::new(&[], &config, &[]).matching_attributes(CustomAttributeKind::Type, fqn)
}

#[test]
fn test_import_collection_does_not_count_as_attribute_emission() {
let config = CodeGenConfig {
type_attributes: vec![(".pkg.Msg".into(), "#[derive(Hash)]".into())],
..CodeGenConfig::default()
};
let ctx = CodeGenContext::new(&[], &config, &[]);
ctx.imports_begin_collecting();
ctx.matching_attributes(CustomAttributeKind::Type, "pkg.Msg")
.unwrap();
ctx.warn_unmatched_custom_attributes();
assert!(matches!(
ctx.take_warnings().as_slice(),
[crate::CodeGenWarning::CustomAttributeRuleMatchedNothing {
option: "type_attributes",
..
}]
));
ctx.imports_take_collected();
ctx.matching_attributes(CustomAttributeKind::Type, "pkg.Msg")
.unwrap();
ctx.warn_unmatched_custom_attributes();
assert!(ctx.take_warnings().is_empty());
}

#[test]
fn test_matching_attributes_catchall() {
// "." matches every type.
let attrs = vec![(".".into(), "#[derive(Foo)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
let result = 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();
let result = 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();
let result = matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.to_string().contains("derive"));
}

#[test]
fn test_matching_attributes_no_partial_segment_match() {
// ".my.pk" must not match ".my.pkg" (partial segment).
let attrs = vec![(".my.pk".into(), "#[derive(Bad)]".into())];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
let result = 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();
let result = matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
assert!(result.is_empty());
}

Expand All @@ -3704,7 +3810,7 @@ mod tests {
(".".into(), "#[derive(A)]".into()),
(".my.pkg".into(), "#[derive(B)]".into()),
];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
let result = matching_attributes(&attrs, "my.pkg.MyMessage").unwrap();
let s = result.to_string();
assert!(s.contains("A") && s.contains("B"));
}
Expand All @@ -3714,7 +3820,7 @@ mod tests {
// Unparseable attributes surface as a hard error so the user sees
// the problem at build time rather than a silently-dropped attribute.
let attrs = vec![(".".into(), "not valid {{{{".into())];
let err = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap_err();
let err = matching_attributes(&attrs, "my.pkg.Msg").unwrap_err();
assert!(matches!(
err,
crate::CodeGenError::InvalidCustomAttribute { .. }
Expand All @@ -3724,7 +3830,7 @@ mod tests {
/// The `detail` of the error `matching_attributes` gives for `attribute`.
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") {
match matching_attributes(&attrs, "my.pkg.Msg") {
Err(crate::CodeGenError::InvalidCustomAttribute {
path,
attribute: reported,
Expand Down Expand Up @@ -3789,7 +3895,7 @@ mod tests {
#[cfg_attr(feature = \"json\", serde(default))]"
.into(),
)];
let result = CodeGenContext::matching_attributes(&attrs, "my.pkg.Msg").unwrap();
let result = 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
Expand Down
12 changes: 3 additions & 9 deletions buffa-codegen/src/enumeration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::generated::descriptor::EnumDescriptorProto;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};

use crate::context::CodeGenContext;
use crate::context::{CodeGenContext, CustomAttributeKind};
use crate::features::ResolvedFeatures;
use crate::CodeGenError;

Expand Down Expand Up @@ -370,14 +370,8 @@ 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(CustomAttributeKind::Type, proto_fqn)?;
let custom_enum_attrs = ctx.matching_attributes(CustomAttributeKind::Enum, proto_fqn)?;

// A `skip_debug` rule naming the enum leaves `Debug` to the consuming
// crate.
Expand Down
25 changes: 24 additions & 1 deletion buffa-codegen/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1515,7 +1515,9 @@ pub struct CodeGenConfig {
/// `"#[derive(serde::Serialize)]"`). [`generate`] returns
/// [`CodeGenError::InvalidCustomAttribute`] for any other string, an
/// empty one included. The same rule holds for the five attribute lists
/// below.
/// below. A valid rule matching no generated target produces
/// [`CodeGenWarning::CustomAttributeRuleMatchedNothing`] through
/// [`generate_with_diagnostics`]; [`generate`] discards warnings.
///
/// When using a custom `serde::Serialize` derive, follow the requirements
/// documented by `buffa_build::Config::type_attribute`: disable
Expand Down Expand Up @@ -2460,6 +2462,20 @@ pub enum CodeGenWarning {
/// so, in place of the path hint.
matches_ungenerated: bool,
},
/// A custom attribute rule matched no target emitted by this generation
/// call. Usually a typo, the wrong attribute list, a oneof variant path
/// instead of its struct-field path, or a rule for an ungenerated import.
///
/// Each list has its own target set; view families, synthetic map-entry
/// messages and synthetic optional oneofs do not create matches.
/// One diagnostic is returned per unmatched list entry, duplicates included.
#[non_exhaustive]
CustomAttributeRuleMatchedNothing {
/// The rule's path as configured.
rule: String,
/// The attribute list in [`CodeGenConfig`], e.g. `"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
Expand Down Expand Up @@ -2546,6 +2562,12 @@ impl core::fmt::Display for CodeGenWarning {
`.generate_json(true)`; plugin: `json=true`)"
)
}
Self::CustomAttributeRuleMatchedNothing { rule, option } => write!(
f,
"{option} rule `{rule}` matched no generated target; check the proto \
path and the attribute list's target kind (only generated owned \
types, fields and oneof variants receive custom attributes)"
),
Self::LazyViewsRequireViews => {
write!(
f,
Expand Down Expand Up @@ -3716,6 +3738,7 @@ pub fn generate_with_diagnostics(
)?;
}

ctx.warn_unmatched_custom_attributes();
Ok((output, ctx.take_warnings()))
}

Expand Down
17 changes: 8 additions & 9 deletions buffa-codegen/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ use crate::generated::descriptor::DescriptorProto;
use proc_macro2::{Ident, TokenStream};
use quote::{format_ident, quote};

use crate::context::{ancillary_prefix, AncillaryKind, CodeGenContext, MessageScope};
use crate::context::{
ancillary_prefix, AncillaryKind, CodeGenContext, CustomAttributeKind, MessageScope,
};
use crate::defaults::parse_default_value;
use crate::features::ResolvedFeatures;
use crate::impl_message::{is_explicit_presence_scalar, is_real_oneof_member};
Expand Down Expand Up @@ -281,8 +283,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(
CustomAttributeKind::OneofStructField,
&format!("{proto_fqn}.{oneof_name}"),
)?;
let tokens = quote! {
Expand Down Expand Up @@ -574,10 +576,8 @@ fn generate_message_with_nesting(
} else {
quote! {}
};
let custom_type_attrs =
CodeGenContext::matching_attributes(&ctx.config.type_attributes, proto_fqn)?;
let custom_message_attrs =
CodeGenContext::matching_attributes(&ctx.config.message_attributes, proto_fqn)?;
let custom_type_attrs = ctx.matching_attributes(CustomAttributeKind::Type, proto_fqn)?;
let custom_message_attrs = ctx.matching_attributes(CustomAttributeKind::Message, proto_fqn)?;
let custom_deserialize = if needs_custom_deserialize {
crate::feature_gates::cfg_block(
generate_custom_deserialize(
Expand Down Expand Up @@ -2045,8 +2045,7 @@ fn generate_field(
} else {
quote! {}
};
let custom_field_attrs =
CodeGenContext::matching_attributes(&ctx.config.field_attributes, &field_fqn)?;
let custom_field_attrs = ctx.matching_attributes(CustomAttributeKind::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
Expand Down
Loading
Loading