codegen_rs/
enum.rs

1use std::fmt;
2
3use crate::formatter::Formatter;
4use crate::type_def::TypeDef;
5use crate::variant::Variant;
6
7use crate::r#type::Type;
8
9/// Defines an enumeration.
10#[derive(Debug, Clone)]
11pub struct Enum {
12    type_def: TypeDef,
13    variants: Vec<Variant>,
14}
15
16impl Enum {
17    /// Return a enum definition with the provided name.
18    pub fn new(name: &str) -> Self {
19        Self {
20            type_def: TypeDef::new(name),
21            variants: vec![],
22        }
23    }
24
25    /// Return a mutable reference to the type definition.
26    pub fn type_def_mut(&mut self) -> &mut TypeDef {
27        &mut self.type_def
28    }
29
30    /// Returns a reference to the type.
31    pub const fn ty(&self) -> &Type {
32        &self.type_def.ty
33    }
34
35    /// Set the enum visibility.
36    pub fn vis(&mut self, vis: &str) -> &mut Self {
37        self.type_def.vis(vis);
38        self
39    }
40
41    /// Add a generic to the enum.
42    pub fn generic(&mut self, name: &str) -> &mut Self {
43        self.type_def.ty.generic(name);
44        self
45    }
46
47    /// Add a `where` bound to the enum.
48    pub fn bound<T>(&mut self, name: &str, ty: T) -> &mut Self
49    where
50        T: Into<Type>,
51    {
52        self.type_def.bound(name, ty);
53        self
54    }
55
56    /// Set the enum documentation.
57    pub fn doc(&mut self, docs: &str) -> &mut Self {
58        self.type_def.doc(docs);
59        self
60    }
61
62    /// Add a new type that the struct should derive.
63    pub fn derive(&mut self, name: &str) -> &mut Self {
64        self.type_def.derive(name);
65        self
66    }
67
68    /// Specify lint attribute to supress a warning or error.
69    pub fn allow(&mut self, allow: &str) -> &mut Self {
70        self.type_def.allow(allow);
71        self
72    }
73
74    /// Specify representation.
75    pub fn repr(&mut self, repr: &str) -> &mut Self {
76        self.type_def.repr(repr);
77        self
78    }
79
80    /// Push a variant to the enum, returning a mutable reference to it.
81    pub fn new_variant(&mut self, name: &str) -> &mut Variant {
82        self.push_variant(Variant::new(name));
83        self.variants.last_mut().unwrap()
84    }
85
86    /// Push a variant to the enum.
87    pub fn push_variant(&mut self, item: Variant) -> &mut Self {
88        self.variants.push(item);
89        self
90    }
91
92    /// Formats the enum using the given formatter.
93    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
94        self.type_def.fmt_head("enum", &[], fmt)?;
95
96        fmt.block(|fmt| {
97            for variant in &self.variants {
98                variant.fmt(fmt)?;
99            }
100
101            Ok(())
102        })
103    }
104}