Skip to content
Closed
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
13 changes: 13 additions & 0 deletions src/struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ pub struct Struct {

/// Struct fields
fields: Fields,

/// The attributes for this struct.
attributes: Vec<String>,
}

impl Struct {
Expand All @@ -22,6 +25,7 @@ impl Struct {
Struct {
type_def: TypeDef::new(name),
fields: Fields::Empty,
attributes: vec![],
}
}

Expand Down Expand Up @@ -63,6 +67,12 @@ impl Struct {
self
}

/// Adds an attribute to the struct (e.g. `"#[some_attribute]"`)
pub fn attribute(&mut self, attribute: &str) -> &mut Self {
self.attributes.push(attribute.to_string());
self
}

/// Specify lint attribute to supress a warning or error.
pub fn allow(&mut self, allow: &str) -> &mut Self {
self.type_def.allow(allow);
Expand Down Expand Up @@ -110,6 +120,9 @@ impl Struct {

/// Formats the struct using the given formatter.
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
for m in self.attributes.iter() {
write!(fmt, "{}\n", m)?;
}
self.type_def.fmt_head("struct", &[], fmt)?;
self.fields.fmt(fmt)?;

Expand Down
38 changes: 38 additions & 0 deletions tests/codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,44 @@ struct Foo {
assert_eq!(scope.to_string(), &expect[1..]);
}

#[test]
fn struct_with_attribute() {
let mut scope = Scope::new();
let mut struct_ = Struct::new("Foo");
let field = Field::new("one", "usize");
struct_.push_field(field);
struct_.attribute("#[test]");
scope.push_struct(struct_);

let expect = r#"
#[test]
struct Foo {
one: usize,
}"#;

assert_eq!(scope.to_string(), &expect[1..]);
}

#[test]
fn struct_with_multiple_attributes() {
let mut scope = Scope::new();
let mut struct_ = Struct::new("Foo");
let field = Field::new("one", "usize");
struct_.push_field(field);
struct_.attribute("#[test]");
struct_.attribute("#[cfg(target_os = \"linux\")]");
scope.push_struct(struct_);

let expect = r#"
#[test]
#[cfg(target_os = "linux")]
struct Foo {
one: usize,
}"#;

assert_eq!(scope.to_string(), &expect[1..]);
}

#[test]
fn single_struct_documented_field() {
let mut scope = Scope::new();
Expand Down