use std::fmt::{self, Write};
use crate::{
Attribute, BaseType, DocComment, Format, Formatter, Type, declare_with, has_annotations,
write_annotations,
};
use tamacro::DisplayFromFormat;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregateKind {
Struct,
Union,
}
impl AggregateKind {
fn keyword(self) -> &'static str {
match self {
AggregateKind::Struct => "struct",
AggregateKind::Union => "union",
}
}
}
#[derive(Debug, Clone)]
pub struct AnonAggregate {
pub kind: AggregateKind,
pub fields: Vec<Field>,
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Struct {
name: String,
body: Option<Vec<Field>>,
attrs: Vec<Attribute>,
raw_attrs: Vec<String>,
doc: Option<DocComment>,
}
impl Struct {
pub fn new(name: String) -> StructBuilder {
StructBuilder::new(name)
}
pub fn to_type(&self) -> Type {
Type::new(BaseType::Struct(self.name.clone())).build()
}
}
impl Format for Struct {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if let Some(doc) = &self.doc {
doc.format(fmt)?;
}
write!(fmt, "struct")?;
if has_annotations(&self.raw_attrs, &self.attrs) {
write!(fmt, " ")?;
write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
}
write!(fmt, " {}", self.name)?;
if let Some(fields) = &self.body {
fmt.block(|fmt| {
for field in fields {
field.format(fmt)?;
}
Ok(())
})?;
}
writeln!(fmt, ";")
}
}
pub struct StructBuilder {
name: String,
fields: Vec<Field>,
force_forward: bool,
force_body: bool,
attrs: Vec<Attribute>,
raw_attrs: Vec<String>,
doc: Option<DocComment>,
}
impl StructBuilder {
pub fn new(name: String) -> Self {
Self {
name,
fields: vec![],
force_forward: false,
force_body: false,
attrs: vec![],
raw_attrs: vec![],
doc: None,
}
}
pub fn new_with_str(name: &str) -> Self {
Self::new(name.to_string())
}
pub fn doc(mut self, doc: DocComment) -> Self {
self.doc = Some(doc);
self
}
pub fn field(mut self, field: Field) -> Self {
self.fields.push(field);
self
}
pub fn fields(mut self, fields: Vec<Field>) -> Self {
self.fields = fields;
self
}
pub fn forward_declaration(mut self) -> Self {
self.force_forward = true;
self
}
pub fn define(mut self) -> Self {
self.force_body = true;
self
}
pub fn attr(mut self, attr: Attribute) -> Self {
self.attrs.push(attr);
self
}
pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
self.attrs = attrs;
self
}
pub fn raw_attr(mut self, token: &str) -> Self {
self.raw_attrs.push(token.to_string());
self
}
pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
self.raw_attrs = tokens;
self
}
pub fn build(self) -> Struct {
let body = if self.force_forward {
None
} else if self.fields.is_empty() && !self.force_body {
None
} else {
Some(self.fields)
};
Struct {
name: self.name,
body,
attrs: self.attrs,
raw_attrs: self.raw_attrs,
doc: self.doc,
}
}
}
#[derive(Debug, Clone, DisplayFromFormat)]
pub struct Field {
pub name: Option<String>,
pub t: Type,
pub anon: Option<AnonAggregate>,
pub width: Option<u8>,
pub attrs: Vec<Attribute>,
pub raw_attrs: Vec<String>,
pub doc: Option<DocComment>,
}
impl Field {
pub fn new(name: String, t: Type) -> FieldBuilder {
FieldBuilder::new(name, t)
}
pub fn anonymous_struct(fields: Vec<Field>) -> FieldBuilder {
FieldBuilder::anonymous(AggregateKind::Struct, fields)
}
pub fn anonymous_union(fields: Vec<Field>) -> FieldBuilder {
FieldBuilder::anonymous(AggregateKind::Union, fields)
}
pub fn to_type(&self) -> Type {
self.t.clone()
}
}
impl Format for Field {
fn format(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
if let Some(doc) = &self.doc {
doc.format(fmt)?;
}
match &self.anon {
None => {
write!(
fmt,
"{}",
declare_with(&self.t, self.name.as_deref().unwrap_or(""), fmt.options())
)?;
if let Some(w) = self.width {
write!(fmt, " : {w}")?;
}
}
Some(agg) => {
write!(fmt, "{}", agg.kind.keyword())?;
fmt.block(|fmt| {
for field in &agg.fields {
field.format(fmt)?;
}
Ok(())
})?;
if let Some(name) = &self.name {
write!(fmt, " {name}")?;
}
}
}
if has_annotations(&self.raw_attrs, &self.attrs) {
write!(fmt, " ")?;
write_annotations(fmt, &self.raw_attrs, &self.attrs)?;
}
writeln!(fmt, ";")
}
}
pub struct FieldBuilder {
name: Option<String>,
t: Type,
anon: Option<AnonAggregate>,
width: Option<u8>,
attrs: Vec<Attribute>,
raw_attrs: Vec<String>,
doc: Option<DocComment>,
}
impl FieldBuilder {
pub fn new(name: String, t: Type) -> Self {
Self {
name: Some(name),
t,
anon: None,
width: None,
attrs: vec![],
raw_attrs: vec![],
doc: None,
}
}
pub fn anonymous(kind: AggregateKind, fields: Vec<Field>) -> Self {
Self {
name: None,
t: Type::new(BaseType::Void).build(),
anon: Some(AnonAggregate { kind, fields }),
width: None,
attrs: vec![],
raw_attrs: vec![],
doc: None,
}
}
pub fn new_with_str(name: &str, t: Type) -> Self {
Self::new(name.to_string(), t)
}
pub fn doc(mut self, doc: DocComment) -> Self {
self.doc = Some(doc);
self
}
pub fn bitfield_width(mut self, width: u8) -> Self {
self.width = Some(width);
self
}
pub fn member_name(mut self, name: &str) -> Self {
self.name = Some(name.to_string());
self
}
pub fn attr(mut self, attr: Attribute) -> Self {
self.attrs.push(attr);
self
}
pub fn attrs(mut self, attrs: Vec<Attribute>) -> Self {
self.attrs = attrs;
self
}
pub fn raw_attr(mut self, token: &str) -> Self {
self.raw_attrs.push(token.to_string());
self
}
pub fn raw_attrs(mut self, tokens: Vec<String>) -> Self {
self.raw_attrs = tokens;
self
}
pub fn build(self) -> Field {
Field {
name: self.name,
t: self.t,
anon: self.anon,
width: self.width,
attrs: self.attrs,
raw_attrs: self.raw_attrs,
doc: self.doc,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::*;
#[test]
fn field() {
let f = FieldBuilder::new_with_str("some_field", Type::new(BaseType::Char).build())
.doc(DocComment::new().line_str("Hello").build())
.build();
let res = r#"/// Hello
char some_field;
"#;
assert_eq!(f.to_string(), res);
let f2 = FieldBuilder::new_with_str("another_field", Type::new(BaseType::Bool).build())
.bitfield_width(1)
.build();
let res2 = "bool another_field : 1;\n";
assert_eq!(f2.to_string(), res2);
}
#[test]
fn structs() {
let s = StructBuilder::new_with_str("Person")
.fields(vec![
FieldBuilder::new_with_str(
"name",
Type::new(BaseType::Char).make_pointer().build(),
)
.build(),
FieldBuilder::new_with_str("age", Type::new(BaseType::UInt8).build()).build(),
])
.build();
let res = r#"struct Person {
char *name;
uint8_t age;
};
"#;
assert_eq!(s.to_string(), res);
}
#[test]
fn anonymous_union_member() {
let s = StructBuilder::new_with_str("Value")
.field(FieldBuilder::new_with_str("tag", Type::new(BaseType::Int).build()).build())
.field(
Field::anonymous_union(vec![
FieldBuilder::new_with_str("i", Type::new(BaseType::Int).build()).build(),
FieldBuilder::new_with_str("d", Type::new(BaseType::Double).build()).build(),
])
.build(),
)
.build();
let res = r#"struct Value {
int tag;
union {
int i;
double d;
};
};
"#;
assert_eq!(s.to_string(), res);
}
#[test]
fn named_inline_aggregate() {
let f = Field::anonymous_struct(vec![
FieldBuilder::new_with_str("x", Type::new(BaseType::Int).build()).build(),
FieldBuilder::new_with_str("y", Type::new(BaseType::Int).build()).build(),
])
.member_name("point")
.build();
let res = r#"struct {
int x;
int y;
} point;
"#;
assert_eq!(f.to_string(), res);
}
#[test]
fn struct_and_field_attributes() {
let s = StructBuilder::new_with_str("Header")
.attr(Attribute::packed())
.field(
FieldBuilder::new_with_str("magic", Type::new(BaseType::UInt32).build())
.attr(Attribute::aligned(4))
.build(),
)
.build();
let res = r#"struct __attribute__((packed)) Header {
uint32_t magic __attribute__((aligned(4)));
};
"#;
assert_eq!(s.to_string(), res);
let c23 = render(
&s,
RenderOptions {
attr_style: AttrStyle::C23,
..Default::default()
},
);
let expected = r#"struct [[gnu::packed]] Header {
uint32_t magic [[gnu::aligned(4)]];
};
"#;
assert_eq!(c23, expected);
}
#[test]
fn raw_annotations() {
let s = StructBuilder::new_with_str("Regs")
.raw_attr("MYLANG_PACKED")
.field(
FieldBuilder::new_with_str("flags", Type::new(BaseType::UInt32).build())
.raw_attr("MYLANG_ALIGN4")
.build(),
)
.build();
let res = r#"struct MYLANG_PACKED Regs {
uint32_t flags MYLANG_ALIGN4;
};
"#;
assert_eq!(s.to_string(), res);
let s2 = StructBuilder::new_with_str("S")
.raw_attr("MYLANG_PACKED")
.attr(Attribute::aligned(8))
.build();
assert_eq!(
s2.to_string(),
"struct MYLANG_PACKED __attribute__((aligned(8))) S;\n"
);
}
#[test]
fn forward_declaration_vs_empty_definition() {
let fwd = StructBuilder::new_with_str("Opaque").build();
assert_eq!(fwd.to_string(), "struct Opaque;\n");
let forced = StructBuilder::new_with_str("Opaque")
.field(FieldBuilder::new_with_str("x", Type::new(BaseType::Int).build()).build())
.forward_declaration()
.build();
assert_eq!(forced.to_string(), "struct Opaque;\n");
let empty = StructBuilder::new_with_str("Empty").define().build();
assert_eq!(empty.to_string(), "struct Empty {\n};\n");
let normal = StructBuilder::new_with_str("P")
.field(FieldBuilder::new_with_str("x", Type::new(BaseType::Int).build()).build())
.build();
assert_eq!(normal.to_string(), "struct P {\n int x;\n};\n");
}
}