1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use super::attributes::{BlockAttribute, FieldAttribute};
use crate::value::{Constant, Documentation, Function};
use std::{borrow::Cow, fmt};

/// A variant declaration in an enum block.
#[derive(Debug)]
pub struct EnumVariant<'a> {
    name: Cow<'a, str>,
    comment_out: bool,
    map: Option<FieldAttribute<'a>>,
    documentation: Option<Documentation<'a>>,
}

impl<'a> EnumVariant<'a> {
    /// Create a new enum variant to be used in an enum declaration.
    ///
    /// ```ignore
    /// enum Foo {
    ///   Bar
    ///   ^^^ value
    /// }
    /// ```
    pub fn new(name: Cow<'a, str>) -> Self {
        Self {
            name,
            comment_out: false,
            map: None,
            documentation: None,
        }
    }

    /// The map attribute of the variant.
    ///
    /// ```ignore
    /// enum Foo {
    ///   Bar @map("foo")
    ///             ^^^ this
    /// }
    /// ```
    pub fn map(&mut self, value: impl Into<Cow<'a, str>>) {
        let mut map = Function::new("map");
        map.push_param(value.into());
        self.map = Some(FieldAttribute::new(map));
    }

    /// Comments the variant out in the declaration.
    ///
    /// ```ignore
    /// enum Foo {
    ///   // Bar
    ///   ^^ adds this
    /// }
    /// ```
    pub fn comment_out(&mut self) {
        self.comment_out = true;
    }

    /// Documentation of a variant.
    ///
    /// ```ignore
    /// enum Foo {
    ///   /// This is the documentation.
    ///   Bar
    /// }
    /// ```
    pub fn documentation(&mut self, documentation: impl Into<Cow<'a, str>>) {
        self.documentation = Some(Documentation(documentation.into()));
    }
}

impl<'a> From<&'a str> for EnumVariant<'a> {
    fn from(variant: &'a str) -> Self {
        Self::new(Cow::Borrowed(variant))
    }
}

impl<'a> fmt::Display for EnumVariant<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(ref docs) = self.documentation {
            docs.fmt(f)?;
        }

        if self.comment_out {
            f.write_str("// ")?;
        }

        f.write_str(&self.name)?;

        if let Some(ref map) = self.map {
            f.write_str(" ")?;
            map.fmt(f)?;
        }

        Ok(())
    }
}

/// An enum block in a PSL file.
#[derive(Debug)]
pub struct Enum<'a> {
    name: Constant<Cow<'a, str>>,
    documentation: Option<Documentation<'a>>,
    variants: Vec<EnumVariant<'a>>,
    map: Option<BlockAttribute<'a>>,
    schema: Option<BlockAttribute<'a>>,
}

impl<'a> Enum<'a> {
    /// Create a new enum declaration block. Will not be valid without
    /// adding at least one variant.
    ///
    /// ```ignore
    /// enum TrafficLight {
    /// //   ^^^^^^^^^^^^ name
    /// }
    /// ```
    pub fn new(name: impl Into<Cow<'a, str>>) -> Self {
        Self {
            name: Constant::new_no_validate(name.into()),
            documentation: None,
            variants: Vec::new(),
            map: None,
            schema: None,
        }
    }

    /// The documentation on top of the enum declaration.
    ///
    /// ```ignore
    /// /// This here is the documentation.
    /// enum Foo {
    ///   Bar
    /// }
    /// ```
    pub fn documentation(&mut self, documentation: impl Into<Cow<'a, str>>) {
        self.documentation = Some(Documentation(documentation.into()));
    }

    /// The schema attribute of the enum block
    ///
    /// ```ignore
    /// enum Foo {
    ///   Bar
    ///
    ///   @@schema("public")
    ///             ^^^^^^ this
    /// }
    /// ```
    pub fn schema(&mut self, schema: impl Into<Cow<'a, str>>) {
        let mut fun = Function::new("schema");
        fun.push_param(schema.into());

        self.schema = Some(BlockAttribute(fun));
    }

    /// Add a new variant to the enum declaration. If passing a string
    /// slice, adds a simple enum variant. Additionally an
    /// `EnumVariant` can be constructed and passed for additional
    /// settings.
    ///
    /// ```ignore
    /// enum Foo {
    ///   Bar
    ///   ^^^ this
    /// }
    /// ```
    pub fn push_variant(&mut self, variant: impl Into<EnumVariant<'a>>) {
        self.variants.push(variant.into());
    }

    /// Sets the block level map attribute.
    ///
    /// ```ignore
    /// enum Foo {
    ///   @@map("bar")
    ///          ^^^ this
    /// }
    /// ```
    pub fn map(&mut self, mapped_name: impl Into<Cow<'a, str>>) {
        let mut fun = Function::new("map");
        fun.push_param(mapped_name.into());

        self.map = Some(BlockAttribute(fun));
    }
}

impl<'a> fmt::Display for Enum<'a> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(doc) = &self.documentation {
            doc.fmt(f)?;
        }

        writeln!(f, "enum {} {{", self.name)?;

        for variant in self.variants.iter() {
            writeln!(f, "{variant}")?;
        }

        if let Some(map) = &self.map {
            writeln!(f, "{map}")?;
        }

        if let Some(schema) = &self.schema {
            writeln!(f, "{schema}")?;
        }

        f.write_str("}\n")?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use expect_test::expect;

    #[test]
    fn kitchen_sink() {
        let mut r#enum = Enum::new("TrafficLight");
        r#enum.map("1TrafficLight");
        r#enum.documentation("Cat's foot, iron claw\nNeuro-surgeons scream for more\nAt paranoia's poison door...");

        r#enum.push_variant("Red");
        {
            let mut green = EnumVariant::new("Green".into());
            green.map("1Green");
            r#enum.push_variant(green);
        }

        let mut variant = EnumVariant::new("Blue".into());
        variant.map("Yellow");
        variant.documentation("Twenty-first century schizoid man!");

        r#enum.push_variant(variant);

        let mut variant = EnumVariant::new("Invalid".into());
        variant.comment_out();
        r#enum.push_variant(variant);
        r#enum.push_variant("Black");

        r#enum.schema("city_planning");

        let expected = expect![[r#"
            /// Cat's foot, iron claw
            /// Neuro-surgeons scream for more
            /// At paranoia's poison door...
            enum TrafficLight {
              Red
              Green @map("1Green")
              /// Twenty-first century schizoid man!
              Blue  @map("Yellow")
              // Invalid
              Black

              @@map("1TrafficLight")
              @@schema("city_planning")
            }
        "#]];

        let rendered = psl::reformat(&format!("{enum}"), 2).unwrap();
        expected.assert_eq(&rendered);
    }
}