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