use std::fmt::{self, Write};
use crate::field::Field;
use crate::fields::Fields;
use crate::formatter::Formatter;
use crate::type_def::TypeDef;
use crate::r#type::Type;
#[derive(Debug, Clone)]
pub struct Struct {
type_def: TypeDef,
fields: Fields,
}
impl Struct {
pub fn new(name: &str) -> Self {
Struct {
type_def: TypeDef::new(name),
fields: Fields::Empty,
}
}
pub fn ty(&self) -> &Type {
&self.type_def.ty
}
pub fn vis(&mut self, vis: &str) -> &mut Self {
self.type_def.vis(vis);
self
}
pub fn generic(&mut self, name: &str) -> &mut Self {
self.type_def.ty.generic(name);
self
}
pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
where
T: Into<Type>,
{
self.type_def.bound(name, ty);
self
}
pub fn doc(&mut self, docs: &str) -> &mut Self {
self.type_def.doc(docs);
self
}
pub fn derive(&mut self, name: &str) -> &mut Self {
self.type_def.derive(name);
self
}
pub fn attr(&mut self, attr: impl Into<String>) -> &mut Self {
self.type_def.attr(attr);
self
}
pub fn allow(&mut self, allow: &str) -> &mut Self {
self.type_def.allow(allow);
self
}
pub fn repr(&mut self, repr: &str) -> &mut Self {
self.type_def.repr(repr);
self
}
pub fn r#macro(&mut self, r#macro: &str) -> &mut Self {
self.type_def.r#macro(r#macro);
self
}
pub fn push_field(&mut self, field: Field) -> &mut Self {
self.fields.push_named(field);
self
}
pub fn field<T>(&mut self, name: &str, ty: T) -> &mut Self
where
T: Into<Type>,
{
self.fields.named(name, ty);
self
}
pub fn new_field<T>(&mut self, name: impl Into<String>, ty: T) -> &mut Field
where
T: Into<Type>,
{
self.fields.new_named(name, ty)
}
pub fn tuple_field<T>(&mut self, ty: T) -> &mut Self
where
T: Into<Type>,
{
self.fields.tuple(ty);
self
}
pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
self.type_def.fmt_head("struct", &[], fmt)?;
self.fields.fmt(fmt)?;
match self.fields {
Fields::Empty => {
write!(fmt, ";\n")?;
}
Fields::Tuple(..) => {
write!(fmt, ";\n")?;
}
_ => {}
}
Ok(())
}
}