Skip to content
Merged
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
21 changes: 15 additions & 6 deletions codama-attributes/src/attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,26 @@ pub enum Attribute<'a> {

impl<'a> Attribute<'a> {
pub fn parse(ast: &'a syn::Attribute, ctx: &AttributeContext) -> syn::Result<Self> {
// Check if the attribute is feature-gated.
let unfeatured = ast.unfeatured();
let attr = unfeatured.as_ref().unwrap_or(ast);
let effective = unfeatured.as_ref().unwrap_or(ast);
Self::parse_from(ast, effective, ctx)
}

let path = attr.path();
/// Parse an attribute using the effective attribute for content extraction.
/// `ast` is stored as the original attribute reference (for error spans).
/// `effective` is used to determine the attribute type and parse its content.
pub fn parse_from(
ast: &'a syn::Attribute,
effective: &syn::Attribute,
ctx: &AttributeContext,
) -> syn::Result<Self> {
let path = effective.path();
match (path.prefix().as_str(), path.last_str().as_str()) {
("" | "codama_macros" | "codama", "codama") => {
Ok(CodamaAttribute::parse(ast, ctx)?.into())
Ok(CodamaAttribute::parse_from(ast, effective, ctx)?.into())
}
("", "derive") => Ok(DeriveAttribute::parse(ast)?.into()),
("", "repr") => Ok(ReprAttribute::parse(ast)?.into()),
("", "derive") => Ok(DeriveAttribute::parse_from(ast, effective)?.into()),
("", "repr") => Ok(ReprAttribute::parse_from(ast, effective)?.into()),
_ => Ok(UnsupportedAttribute::new(ast).into()),
}
}
Expand Down
134 changes: 133 additions & 1 deletion codama-attributes/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,20 @@ impl<'a> Attributes<'a> {
let attributes = Self(
attrs
.iter()
.map(|attr| Attribute::parse(attr, &ctx))
// Expand multi-attr cfg_attr into (ast, effective) pairs
.flat_map(|ast| {
let inners = ast.unfeatured_all();
if inners.len() <= 1 {
// Not a multi-attr cfg_attr - use standard parsing
let unfeatured = ast.unfeatured();
let effective = unfeatured.unwrap_or_else(|| (*ast).clone());
vec![(ast, effective)]
} else {
// Multi-attr cfg_attr - expand each inner attribute
inners.into_iter().map(|inner| (ast, inner)).collect()
}
})
.map(|(ast, effective)| Attribute::parse_from(ast, &effective, &ctx))
.collect_and_combine_errors()?,
);
attributes.validate_codama_type_attributes()?;
Expand Down Expand Up @@ -144,3 +157,122 @@ impl IndexMut<usize> for Attributes<'_> {
&mut self.0[index]
}
}

#[cfg(test)]
mod tests {
use super::*;
use syn::parse_quote;

fn file_ctx() -> syn::File {
syn::File::empty()
}

#[test]
fn parse_single_codama_attr() {
let file = file_ctx();
let attrs: Vec<syn::Attribute> = vec![parse_quote! { #[codama(type = boolean)] }];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

assert_eq!(attributes.len(), 1);
assert!(matches!(&attributes[0], Attribute::Codama(_)));
}

#[test]
fn parse_feature_gated_single_codama_attr() {
let file = file_ctx();
let attrs: Vec<syn::Attribute> =
vec![parse_quote! { #[cfg_attr(feature = "codama", codama(type = boolean))] }];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

assert_eq!(attributes.len(), 1);
assert!(matches!(&attributes[0], Attribute::Codama(_)));
}

#[test]
fn parse_multi_attr_cfg_attr_expands_all() {
let file = file_ctx();
// This is the bug scenario: multi-attr cfg_attr should expand to multiple attributes
let attrs: Vec<syn::Attribute> = vec![parse_quote! {
#[cfg_attr(feature = "codama", codama(type = boolean), codama(name = "foo"))]
}];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

// Should have 2 attributes from the expansion
assert_eq!(attributes.len(), 2);
assert!(matches!(&attributes[0], Attribute::Codama(_)));
assert!(matches!(&attributes[1], Attribute::Codama(_)));

// Verify the directives
if let Attribute::Codama(attr) = &attributes[0] {
assert!(matches!(attr.directive.as_ref(), CodamaDirective::Type(_)));
}
if let Attribute::Codama(attr) = &attributes[1] {
assert!(matches!(attr.directive.as_ref(), CodamaDirective::Name(_)));
}
}

#[test]
fn parse_multi_attr_cfg_attr_mixed_types() {
let file = file_ctx();
// cfg_attr with mixed attribute types: derive, codama
let attrs: Vec<syn::Attribute> = vec![parse_quote! {
#[cfg_attr(feature = "x", derive(Debug), codama(type = boolean))]
}];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

// Should have 2 attributes: Derive and Codama
assert_eq!(attributes.len(), 2);
assert!(matches!(&attributes[0], Attribute::Derive(_)));
assert!(matches!(&attributes[1], Attribute::Codama(_)));
}

#[test]
fn parse_multi_attr_cfg_attr_preserves_order() {
let file = file_ctx();
let attrs: Vec<syn::Attribute> = vec![parse_quote! {
#[cfg_attr(feature = "codama", codama(name = "first"), codama(name = "second"), codama(name = "third"))]
}];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

assert_eq!(attributes.len(), 3);

// All should be Name directives in order
let names: Vec<_> = attributes
.iter()
.filter_map(CodamaAttribute::filter)
.filter_map(|a| {
if let CodamaDirective::Name(n) = a.directive.as_ref() {
Some(n.name.as_ref().to_string())
} else {
None
}
})
.collect();
assert_eq!(names, vec!["first", "second", "third"]);
}

#[test]
fn parse_multiple_separate_cfg_attr_and_multi_attr() {
let file = file_ctx();
// Mix of separate attrs and multi-attr cfg_attr
let attrs: Vec<syn::Attribute> = vec![
parse_quote! { #[derive(Clone)] },
parse_quote! { #[cfg_attr(feature = "x", codama(name = "a"), codama(name = "b"))] },
parse_quote! { #[codama(type = boolean)] },
];
let ctx = AttributeContext::File(&file);
let attributes = Attributes::parse(&attrs, ctx).unwrap();

// Should have 4 attributes: Derive, 2 Codama from cfg_attr, 1 Codama bare
assert_eq!(attributes.len(), 4);
assert!(matches!(&attributes[0], Attribute::Derive(_)));
assert!(matches!(&attributes[1], Attribute::Codama(_)));
assert!(matches!(&attributes[2], Attribute::Codama(_)));
assert!(matches!(&attributes[3], Attribute::Codama(_)));
}
}
18 changes: 13 additions & 5 deletions codama-attributes/src/codama_attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,20 @@ pub struct CodamaAttribute<'a> {

impl<'a> CodamaAttribute<'a> {
pub fn parse(ast: &'a syn::Attribute, ctx: &AttributeContext) -> syn::Result<Self> {
// Check if the attribute is feature-gated.
let unfeatured = ast.unfeatured();
let attr = unfeatured.as_ref().unwrap_or(ast);
let effective = unfeatured.as_ref().unwrap_or(ast);
Self::parse_from(ast, effective, ctx)
}

// Check if the attribute is a #[codama(...)] attribute.
let list = attr.meta.require_list()?;
/// Parse a codama attribute using the effective attribute for content extraction.
/// `ast` is stored as the original attribute reference (for error spans).
/// `effective` is used to parse the actual directive content.
pub fn parse_from(
ast: &'a syn::Attribute,
effective: &syn::Attribute,
ctx: &AttributeContext,
) -> syn::Result<Self> {
let list = effective.meta.require_list()?;
if !list.path.is_strict("codama") {
return Err(list.path.error("expected #[codama(...)]"));
};
Expand All @@ -24,7 +32,7 @@ impl<'a> CodamaAttribute<'a> {
list.each(|ref meta| directive.set(CodamaDirective::parse(meta, ctx)?, meta))?;
Ok(Self {
ast,
directive: Box::new(directive.take(attr)?),
directive: Box::new(directive.take(effective)?),
})
}
}
Expand Down
13 changes: 8 additions & 5 deletions codama-attributes/src/derive_attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,20 @@ pub struct DeriveAttribute<'a> {

impl<'a> DeriveAttribute<'a> {
pub fn parse(ast: &'a syn::Attribute) -> syn::Result<Self> {
// Check if the attribute is feature-gated.
let unfeatured = ast.unfeatured();
let attr = unfeatured.as_ref().unwrap_or(ast);
let effective = unfeatured.as_ref().unwrap_or(ast);
Self::parse_from(ast, effective)
}

// Check if the attribute is a #[derive(...)] attribute.
let list = attr.meta.require_list()?;
/// Parse a derive attribute using the effective attribute for content extraction.
/// `ast` is stored as the original attribute reference (for error spans).
/// `effective` is used to parse the actual derive list.
pub fn parse_from(ast: &'a syn::Attribute, effective: &syn::Attribute) -> syn::Result<Self> {
let list = effective.meta.require_list()?;
if !list.path.is_strict("derive") {
return Err(list.path.error("expected #[derive(...)]"));
};

// Parse the list of derives.
let derives = list.parse_comma_args::<syn::Path>()?;
Ok(Self { ast, derives })
}
Expand Down
13 changes: 8 additions & 5 deletions codama-attributes/src/repr_attribute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,20 @@ pub struct ReprAttribute<'a> {

impl<'a> ReprAttribute<'a> {
pub fn parse(ast: &'a syn::Attribute) -> syn::Result<Self> {
// Check if the attribute is feature-gated.
let unfeatured = ast.unfeatured();
let attr = unfeatured.as_ref().unwrap_or(ast);
let effective = unfeatured.as_ref().unwrap_or(ast);
Self::parse_from(ast, effective)
}

// Check if the attribute is a #[repr(...)] attribute.
let list = attr.meta.require_list()?;
/// Parse a repr attribute using the effective attribute for content extraction.
/// `ast` is stored as the original attribute reference (for error spans).
/// `effective` is used to parse the actual repr list.
pub fn parse_from(ast: &'a syn::Attribute, effective: &syn::Attribute) -> syn::Result<Self> {
let list = effective.meta.require_list()?;
if !list.path.is_strict("repr") {
return Err(list.path.error("expected #[repr(...)]"));
};

// Parse the list of metas.
let metas = list.parse_comma_args::<syn::Meta>()?;
Ok(Self { ast, metas })
}
Expand Down
Loading