Skip to main content

layline_codegen/model/
enumeration.rs

1//! Enumerations.
2
3use alloc::string::String;
4use alloc::vec::Vec;
5
6use super::Derive;
7
8use super::Scalar;
9
10/// An enumeration of named values, with an optional fallback variant for unlisted values.
11#[derive(Debug, Clone, PartialEq, Eq)]
12#[non_exhaustive]
13pub struct EnumDef {
14    /// The type name.
15    pub name: String,
16    /// The value's type.
17    pub repr: Scalar,
18    /// The variants, in declaration order.
19    pub variants: Vec<Variant>,
20    /// The fallback variant, which holds an unlisted value. `None` means every value is listed.
21    pub other: Option<String>,
22    /// Documentation.
23    pub doc: Option<String>,
24    /// The variant marked `#[default]`, which needs an ungated `Default` derive.
25    pub default: Option<String>,
26    /// Derives for this enumeration, written after the module's.
27    pub derives: Vec<Derive>,
28}
29
30impl EnumDef {
31    /// An enumeration with no fallback, so it must list every value.
32    #[must_use]
33    pub fn new(name: &str, repr: Scalar, variants: Vec<Variant>) -> Self {
34        Self {
35            name: String::from(name),
36            repr,
37            variants,
38            other: None,
39            doc: None,
40            default: None,
41            derives: Vec::new(),
42        }
43    }
44
45    /// Marks `variant` `#[default]`, which the derives must match with an ungated `Default`.
46    ///
47    /// The variant must be a listed one, not the fallback, which carries a value.
48    #[must_use]
49    pub fn with_default(self, variant: &str) -> Self {
50        Self { default: Some(String::from(variant)), ..self }
51    }
52
53    /// Sets the derives written on this enumeration, after the module's.
54    #[must_use]
55    pub fn with_derives(self, derives: Vec<Derive>) -> Self {
56        Self { derives, ..self }
57    }
58
59    /// Adds a fallback variant `other(repr)` that holds any unlisted value.
60    #[must_use]
61    pub fn with_other(self, other: &str) -> Self {
62        Self { other: Some(String::from(other)), ..self }
63    }
64
65    /// Sets the documentation.
66    #[must_use]
67    pub fn with_doc(self, doc: &str) -> Self {
68        Self { doc: Some(String::from(doc)), ..self }
69    }
70}
71
72/// One variant of an [`EnumDef`].
73#[derive(Debug, Clone, PartialEq, Eq)]
74#[non_exhaustive]
75pub struct Variant {
76    /// The value on the wire.
77    pub value: i64,
78    /// The variant name.
79    pub name: String,
80    /// Documentation.
81    pub doc: Option<String>,
82}
83
84impl Variant {
85    /// `name = value`, undocumented.
86    #[must_use]
87    pub fn new(value: i64, name: &str) -> Self {
88        Self { value, name: String::from(name), doc: None }
89    }
90
91    /// Sets the documentation.
92    #[must_use]
93    pub fn with_doc(self, doc: &str) -> Self {
94        Self { doc: Some(String::from(doc)), ..self }
95    }
96}